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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP