Java 中的值传递和引用传递
值传递是指使用参数的值来调用方法。通过这种方式,参数的值被传递给方法。
而引用传递是指使用参数的引用来调用方法。通过这种方式,参数的引用被传递给方法。
在值传递中,对传递的参数所做的修改不会反映在调用者的作用域中,而在引用传递中,对传递的参数所做的修改是持久的,并且更改会反映在调用者的作用域中。
以下是值传递的示例:
以下程序展示了一个按值传递参数的示例。即使在方法调用之后,参数的值也保持不变。
示例 - 值传递
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); // Invoke the swap method 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); // Swap n1 with 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
示例 - 引用传递
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); // Invoke the swap method swapFunction(a, b); System.out.println("
**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); // Swap n1 with n2 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
广告