Java中如何声明、定义和调用方法?
以下是在Java中声明方法的语法。
语法
modifier return_type method_name(parameters_list){
//方法体
}在哪里,
修饰符-它定义了方法的访问类型,并且可以选择使用。
return_type-方法可能返回一个值。
method_name-这是方法名称。方法签名由方法名称和参数列表组成。
parameters_list-参数列表,它是方法的类型、顺序和参数数量。这些是可选的,方法可能包含零个参数。
方法体-方法体定义了方法对语句的作用。
调用方法
对于使用方法,应该调用它。调用方法有两种方式,即方法返回值或不返回任何内容(无返回值)。
示例
以下是演示如何定义方法以及如何调用它的示例-
public class ExampleMinNumber {
public static void main(String[] args) {
int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}
/** Returns the minimum of two numbers */
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2){
min = n2;
} else {
min = n1;
}
return min;
}
}输出结果Minimum value = 6
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短