How to define and call methods in Java?
In Java, methods are defined and called as follows:
- Definition of a method:
The definition of a method includes the method’s name, parameters, and return type. The general syntax for defining a method is as follows:
<返回类型> <方法名称>(<参数列表>) {
// 方法体
// 可以包含一段或多段代码
// 方法可能会返回一个值
}
Among them:
: Specifies the return type of the method, which can be any valid data type. If the method does not return any value, the keyword void can be used. : Specifies the name of the method, which can be named using any valid identifier. : Specifies the method’s parameters, which can include zero or more parameters. Each parameter is comprised of a type and a name, separated by commas.
Here is a definition of a method that calculates the sum of two integers:
int sum(int a, int b) {
int result = a + b;
return result;
}
- Method invocation:
In Java, you can call a method by its name and the parameters passed to it. The general syntax for method invocation is as follows:
<方法名称>(<参数列表>);
For example, the sum method defined above can be called in the following way:
int result = sum(3, 4);
System.out.println(result); // 输出结果为 7
When calling a method, you can assign the return value of the method to a variable and use this variable in the subsequent code.
In addition to regular method calls, you can also use object method calls and static method calls. Object method call refers to calling a method through an object, while a static method call refers to calling a method through a class name. The specific way of calling a method depends on the method’s modifiers and whether it belongs to an instance of a class.