All Java method arguments are passed by value. However, Java does manipulate objects by reference, and all object variables themselves are references.(摘自http://www.javagalaxy.com:8080/Interview/index.jsp?Intv=18)
Java中所有方法的參數都是傳值的。 然而,Java確實是通過引用來操作對象的,並且所有的物件變數本身都是引用。
原來所有方法都是傳值,不存在傳引用之說!
舉幾個例子看看:
例子1:
public class TestRef1 {
public static void test(StringBuffer str) {
str = new StringBuffer(", World!");
}
public static void main(String[] args) {
StringBuffer string = new StringBuffer("Hello");
test(string);
System.out.println(string);
}
}
運行結果:Hello
例子2:
public class TestRef2 {
public static void test(String str) {
str = ", World!";
}
public static void main(String[] args) {
String string = new String("Hello");
test(string);
System.out.println(string);
}
}
運行結果:Hello
例子3:
public class TestRef3 {
public static void test(StringBuffer str) {
str.append(", World!");
}
public static void main(String[] args) {
StringBuffer string = new StringBuffer("Hello");
test(string);
System.out.println(string);
}
運行結果:Hello, World!
首先我認為:上面三個例子都是傳值,沒有傳引用。
其次,我們認為:
1、不同的引用可以指向同一個對象;
2、String 對象的值本身是不可更改的 (像 b = "World"; b = a; 這種情況不是改變了 "World" 這一對象的值,而是改變了它的引用 b 的值使之指向了另一個 String 對象 a);
3、"="是賦值運算子。賦值修改的是對象引用,而不是對象本身。