Java中的方法
Java方法是语句的集合,这些语句被组合在一起以执行操作。让我们没有看到在Java中创建方法的语法-
public static int methodName(int a, int b) {
// body
}这里,
publicstatic-修饰符
int-返回类型
methodName-方法名称
a,b-形式参数
inta,intb-参数列表
方法定义由方法标题和方法主体组成。以下语法显示相同的内容-
modifier returnType nameOfMethod (Parameter List) {
// method body
}上面显示的语法包括-
修饰符-它定义方法的访问类型,并且是可选的。
returnType-方法可以返回一个值。
nameOfMethod-这是方法名称。方法签名由方法名称和参数列表组成。
参数列表-参数列表,它是方法的类型,顺序和参数数量。这些是可选的,方法可能包含零个参数。
方法主体-方法主体定义方法对语句的作用。
现在让我们来看一个使用Java创建和调用方法的示例。在这里,我们还传递参数值-
示例
public class Demo {
public static void main(String[] args) {
int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);
// 调用交换方法
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be same here**:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
//用n2交换n1
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}输出结果
Before swapping, a = 30 and b = 45 Before swapping(Inside), a = 30 b = 45 After swapping(Inside), a = 45 b = 30 **Now, Before and After swapping values will be same here**: After swapping, a = 30 and b is 45