Java method definition and invocation
In Java, functions are referred to as methods. A method is a block of code that encapsulates specific functionality. Methods can be invoked by other code, thereby enabling code reusability and modularity.
Methods in Java typically consist of the following components:
- Method Name: Used to identify the name of the method; it usually follows camel case naming conventions.
- Parameter List: Used to pass data required for executing the method. It can contain zero or more parameters, where each parameter consists of a parameter type and a parameter name.
- Return Type: Specifies the data type returned after the method execution completes. This can be a primitive data type, an object type, or
void(indicating that the method returns no value). - Method Body: Contains the specific implementation code, enclosed in a pair of curly braces.
Methods in Java are categorized into static methods and instance methods. Static methods belong to the class itself and can be invoked directly through the class name. Instance methods require creating an instance of the class first; they must then be called via that object.
Example
The following is an example of a method in Java:
public static int add(int x, int y) {
return x + y; // Returns the sum of x and y
}
This method is named add, has two parameters (x and y) of type int, and its return type is also int. The method body performs an addition operation on x and y and returns the result. This method can be invoked as follows:
int sum = add(2, 3); // Calls add with arguments 2 and 3; assigns the returned value (5) to variable 'sum'
By calling this way, you pass 2 and 3 into the add method, then assign the returned result of $3+2=5$ to the sum variable.