How to define functions in Java?
In Java, you can define functions using the following syntax:
访问修饰符 返回类型 函数名(参数列表) {
// 函数体
// 返回语句
}
Among them:
- Access modifiers can be public, private, or protected, and are used to control the access levels of functions.
- The return type specifies the data type of the value returned by a function, and if a function does not return any value, the keyword void can be used to indicate that.
- A function name is an identifier used to call a function.
- The parameter list consists of the input parameters of a function, which can be zero or more, each parameter consisting of a data type and parameter name, separated by commas.
- The function body contains the actual code logic, which can include a series of statements and control structures.
- The return statement is used to send back results to the caller, and the return value must match the return type.
Here is an example function definition:
public int sum(int a, int b) {
int result = a + b;
return result;
}
In this example, there is a function called “sum” that returns an integer. It takes two integer parameters, “a” and “b”. The function calculates the sum of “a” and “b” in the body, and returns the result to the caller.