How do you define a method in Java?
In Java, the definition of a method includes the following components:
- Access Modifiers: Methods can use access modifiers to control whether other classes can access that method. Common access modifiers include public, private, and protected.
- Return type: A method can have a return type, which specifies the type of value that the method returns. If the method does not return any value, the keyword void can be used.
- Method name: The name of the method, used to reference the method when calling it.
- List of parameters: A method can have zero or multiple parameters to receive values passed by the caller. Each parameter has a type and a name.
- Method body: The method body contains the specific implementation of the method, which is the block of code that the method will execute.
Here is a simple example demonstrating the definition of a method with a return value and parameters:
public class Example {
public static void main(String[] args) {
int result = sum(10, 20);
System.out.println("Sum: " + result);
}
public static int sum(int a, int b) {
return a + b;
}
}
In the example above, a method named sum is defined, which takes two integer parameters a and b, and returns their sum. The sum method is called in the main method and the result is printed out.