java中的String類的不可變性的小例子

來源:互聯網
上載者:User

標籤:images   alt   函數參數   參考型別   語言   code   一個   常量   變化   

在java語言中,String類具有不可變性,即常量字串不可更改。下面的一個小例子簡單示範相關概念。

 1 public class test { 2     public static void main(String []args){ 3         String str1="hello"; 4         System.out.println(str1); 5         tell(str1); 6         System.out.print(str1);     7     } 8      9     public static void tell(String str)10     {11         str="main";12     }13 14 }

輸出結果:

1 hello2 hello

從輸出可以看出,str1的值並沒有改變,這是因為在java語言中,參考型別的資料作為函數參數傳遞時,雖然依然採用值傳遞的方法,但傳遞的資料是一個引用,即將str1指向的“hello”的地址傳遞給tell方法,在tell方法中更改的指向只是將str1的複製,在tell方法開始時,str1複製給str2,然後,str2指向“main”,這時str1的指向並沒有改變,到tell方法結束後,str1 的輸出結果仍然是“hello”;

 1 public class test { 2      3     public static void main(String []args){ 4         String str1="hello"; 5         System.out.println(str1); 6  7         str1="main"; 8         System.out.print(str1);             9     }10 }

輸出結果

hellomain

從輸出結果上來看,似乎str1的值被改變了,但是事實上只是將str1的指向由“hello”變成了“mian”,“hello”字串並沒有改變。

 

java中的String類的不可變性的小例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.