Java Function Structure and Usage
Java functions are collections of statements that perform a specific task. They are similar to functions in other programming languages.
- A function is an ordered set of steps to solve a particular problem.
- Functions are contained within classes or objects.
- Functions are created in one part of the program and called from another.
Principle for designing functions: When designing a funcsion, it's best to keep it atomic.
A function consists of the following components:
- Modifiers: Inform the compiler about how the method can be accessed. Defines the access type of the method.
- Return type: Most functions return a value. The return type specifies the data type of the value returned by the function. Some functions do not return any value, in which case the return type is the keyword void.
- Method name: The actual name of the method. The method name and parameter list together form the method signature (remember to follow naming conventions: camel case).
- Parameter types: Parameters act as placeholders. When a method is called, value are passed to the parameetrs. These values are called arguments. The parameter list refers to the number, order, and data types of the parameters. Parameters are optional; a method may have no parameters at all.
- Formal parameters: Used to receive external input when a method is called.
- Arguments: Data actually passed to a method during its invocation.
- Method body: Contains the specific statements that define the function's behavior.
modifier return_type method_name(parameter_type parameter_name) {
// method body
return value; // if the return type is void, this line is not required.
}
Example:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
int y = scanner.nextInt();
int result = findMaximum(x, y);
System.out.println(result);
}
// Compare two numbers
public static int findMaximum(int value1, int value2) {
if (value1 > value2) {
return value1;
} else if (value1 < value2) {
return value2;
} else {
System.out.println("Numbers are equal");
return 0; // exit the method
}
}
In the example, the main method calls the findMaximum method. The purpose of findMaximum is to compare two input numbers and return the larger one. The method returns an integer value, and value1 and value2 are formal parameters. In the main method, x and y are the actual arguments.