Java Methods Explained
In Java, a method is a group of statements that perform a specific task and return a result to the caller. They allow us to reuse code without having to write it again. Every method in Java must be part of a class, which is different from other programming languages like C++, Python, and C.
Declaring a Method
When declaring a method in Java, there are six components that need to be defined:
Modifier: Defines the access type of the method, i.e. where it can be accessed in your application. There are four types of access specifiers in Java: public, protected, private, and default.
Return Type: The data type of the value returned by the method or void if the method does not return a value.
Method Name: The name of the method. The rules for field names apply to method names as well, but the convention is slightly different.
Parameter List: Comma-separated list of input parameters defined by their data type, enclosed in parentheses. If there are no parameters, empty parentheses are used.
Exception List: The exceptions that the method can throw, which can be specified.
Method Body: The code that needs to be executed to perform the intended operations, enclosed in braces.
Method Signature
The method signature consists of the method name and parameter list, including the number of parameters, the type of parameters, and their order. Return type and exceptions are not part of the method signature.
Naming a Method
A method name is usually a single word that should be a verb in lowercase or a multi-word name that begins with a verb in lowercase followed by an adjective, noun, etc. After the first word, the first letter of each word should be capitalized. For example, findSum, computeMax, setX, and getX.
Method Overloading
A method in Java can have the same name as another method within the same class due to method overloading. Overloaded methods are differentiated based on the number and type of parameters passed as arguments to the methods.
Calling a Method
To use a method's functionality, the method needs to be called. A method returns to the code that invoked it when it completes all statements in the method, reaches a return statement, or throws an exception.
Static Methods
A method can be declared static using the static keyword, which means it belongs to the class and can be called without making an object of the same class.
Java is Strictly Pass by Value
Java is strictly pass by value, which means that the method cannot modify the value of the variables passed to it.
Method Overriding
A method can be declared abstract using the abstract keyword and final using the final keyword, but it cannot be both simultaneously. It is also not possible to overload or override static methods in Java.
Null Errors in Java
Null errors can occur when trying to access a null object or null pointer. It is important to check for null values before using them in a method.