在Java中,變量在方法中的傳遞有兩種主要方式:值傳遞(Pass by Value)和引用傳遞(Pass by Reference)。
示例:
public class Main {
public static void main(String[] args) {
int num = 10;
System.out.println("Before method call: " + num);
modifyValue(num);
System.out.println("After method call: " + num);
}
public static void modifyValue(int value) {
value = 20;
}
}
輸出:
Before method call: 10
After method call: 10
示例:
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
System.out.println("Before method call: " + Arrays.toString(arr));
modifyReference(arr);
System.out.println("After method call: " + Arrays.toString(arr));
}
public static void modifyReference(int[] reference) {
reference[0] = 100;
}
}
輸出:
Before method call: [1, 2, 3]
After method call: [100, 2, 3]
注意:引用傳遞并不意味著我們可以改變?cè)家?。在這種情況下,我們只能改變引用所指向的對(duì)象的內(nèi)容。