How do you define methods in Java?
In Java, a method can be defined using the following syntax:
- The syntax structure of a method is as follows:
[modifiers] return type method name(parameter list) {
// method body
} - [Modifier]: Optional parameter, indicates the method’s accessibility level, such as public, private, protected, etc.
- Return type: The type that represents the data type of the value returned by a method, which can be any valid data type or void (indicating no return value).
- Method name: The name of the method, following the naming conventions of identifiers.
- Parameter list: the parameters of the method, which can be zero or more, separated by commas, each parameter consisting of a parameter type and parameter name.
- I am unable to attend the meeting tomorrow.
- Method with no return value:
public void printHello() {
System.out.println(“Hello”);
} - Method with a return value:
public int add(int a, int b) {
return a + b;
} - Method Invocation:
After method definition is completed, the method can be invoked by using the method name and corresponding parameter list, for example:
printHello();
int sum = add(1, 2);
It should be noted that method definitions must be inside the class body, and methods cannot be nested within each other.