在按值传递参数时需要传递参数。它们的顺序应与方法规范中的参数顺序相同。参数可以通过值或引用传递。
通过值传递参数是使用参数调用方法。 通过这样将参数值将传递给参数。
示例
以下程序显示了按值传递参数的示例。 即使在方法调用之后,参数的值仍保持不变。
public class swappingExample { 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("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); // 交换 n1 和 n2 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