在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]
注意:引用传递并不意味着我们可以改变原始引用。在这种情况下,我们只能改变引用所指向的对象的内容。