Java是傳值還是傳引用

來源:互聯網
上載者:User
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、"="是賦值運算子。賦值修改的是對象引用,而不是對象本身。

按照上面所說,
1、str = ", World!";和str = new StringBuffer(", World!");都是賦值操作,修改的是對象str的引用,使之指向新的一個對象,而沒有改變對象本身(這裡分別是", World!"和new StringBuffer(", World!"))。所以string不受其影響。
2、str.append(", World!");這個改的是對象本身,而非對象引用。

以上都是個人觀點,歡迎指正!





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.