按值调用意味着调用以参数为值的方法。通过此操作,参数值将传递给参数。
而“按引用调用”是指以参数为参考来调用方法。通过此操作,参数引用将传递给参数。
在按值调用中,对传递的参数所做的修改不会反映在调用者的作用域中,而在按引用进行的调用中,对传递的参数所做的修改是持久性的,而更改则反映在调用者的作用域中。
以下是按值调用的示例-
以下程序显示了通过值传递参数的示例。即使在方法调用之后,参数的值仍保持不变。
public class Tester{ 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
Java在传递引用变量的同时也仅使用按值调用。它创建引用的副本,并将它们作为有值的方法传递给方法。由于引用指向对象的相同地址,因此创建引用副本是没有害处的。但是,如果将新对象分配给引用,则不会反映出来。
public class JavaTester { public static void main(String[] args) { IntWrapper a = new IntWrapper(30); IntWrapper b = new IntWrapper(45); System.out.println("Before swapping, a = " + a.a + " and b = " + b.a); //调用交换方法 swapFunction(a, b); System.out.println("\n**Now, Before and After swapping values will be different here**:"); System.out.println("After swapping, a = " + a.a + " and b is " + b.a); } public static void swapFunction(IntWrapper a, IntWrapper b) { System.out.println("Before swapping(Inside), a = " + a.a + " b = " + b.a); //用n2交换n1- IntWrapper c = new IntWrapper(a.a); a.a = b.a; b.a = c.a; System.out.println("After swapping(Inside), a = " + a.a + " b = " + b.a); } } class IntWrapper { public int a; public IntWrapper(int a){ this.a = a;} }
这将产生以下结果-
输出结果
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 different here**: After swapping, a = 45 and b is 30