Java裏方法的參數傳遞只有一種:值傳遞。就是將實際參數值的副本(複製品)傳入方法內,而參數本身不會受到任何影響。
1、基本類型參數傳遞
public class valueTransmit {
public static void main(String[] args) {
int a = 6;
int b = 9;
System.out.println("交換前,a的值是:" + a + "; b的值是:" + b);
swap(a, b);
System.out.println("交換結束後,a的值是:" + a + "; b的值是:" + b);
}
public static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
System.out.println("swap方法裏,a的值是:" + a + "; b的值是:" + b);
}
}
運行結果:
交換前,a的值是:6; b的值是:9
swap方法裏,a的值是:9; b的值是:6
交換結束後,a的值是:6; b的值是:9
從運行結果得到:swap()方法的a和b只是main()方法裏變量a和b的複製品。程序改變的是swap方法棧區中的a、b,mian()方法棧區中的a、b都沒有改變。
2、引用類型的參數傳遞:一樣採用的是值傳遞方式
public static void main(String[] args) {
Student student = new Student();
student.high = 6;
student.age = 9;
System.out.println("交換前,high的值是:" + student.high + "; age的值是:" + student.age);
swap(student); // swap方法裏把student賦值爲null,main方法的student變量不受影響
System.out.println("交換後,high的值是:" + student.high + "; age的值是:" + student.age);
}
public static void swap(Student student) {
int temp = student.age;
student.age = student.high;
student.high = temp;
System.out.println("swap方法裏,high的值是:" + student.high + "; age的值是:" + student.age);
student = null;
}
static class Student {
private int high;
private int age;
public int getHigh() {
return high;
}
public void setHigh(int high) {
this.high = high;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
輸出結果:
交換前,high的值是:6; age的值是:9
swap方法裏,high的值是:9; age的值是:6
交換後,high的值是:9; age的值是:6
乍看輸出結果,當swap方法交換了high和age的值,main方法裏high和age的值也交換了。會讓我們誤以爲傳入的student是Student對象本身,而不是它的複製品。
其實不然,首先創建一個對象,內存中會有兩個東西產生:棧內存中保存了該對象的引用變量,堆內存中保存了對象本身。
一開始,main()方法中調用swap()方法,mian()方法尚未結束,jvm會分別爲main()和swap()開闢兩個棧區,用於存放局部變量。調用swap()方法是,student變量作爲實參傳入swap()方法,同樣是值傳遞方式:把實參student賦值給swap方法裏的形參,不過這裏的student是一個引用(也就是c中的指針),保存的是Student對象的地址值,用於找到堆內存的Student對象。所以swap裏面的student也會指向Student對象的堆內存地址。
所以這種引用傳遞方式也是值傳遞,關鍵在於複製的是引用變量的副本,並未複製實際的Student對象。操作的都是同一個對象,因此swap交換後,main方法裏面student的屬性也會改變。
參考書籍:《瘋狂Java講義》