Java基礎之【String爲什麼是immutable】

原文:

https://www.javatpoint.com/immutable-string

In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.

java中,String對象是不可變的,不可變簡單理解就是不能修改或者不能改變

Once string object is created its data or state can't be changed but a new string object is created

以耽String對象被創建它的數據或狀態就不能被改變 除了一個新的對象被創立

下面看例子:

class Testimmutablestring{  
 public static void main(String args[]){  
   String s="Sachin";  
   s.concat(" Tendulkar");//concat() method appends the string at the end  
   System.out.println(s);//will print Sachin because strings are immutable objects  
 }  
}  


輸出:Sachin

上面顯示及concat並沒有起作用

 

再看下面例子:

class Testimmutablestring1{  
 public static void main(String args[]){  
   String s="Sachin";  
   s=s.concat(" Tendulkar");  
   System.out.println(s);  
 }  
}  

輸出:Sachin Tendulkar

In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not modified.

在上面例子,s的應用地址指向了Sachin Tendulkar,但是注意 sachin字符串對象依舊沒有被修改

 

譯者注:

通過String源碼可以看出  private final char value[]; 表明是不可修改的 但是如果看StirngBuffer StringBuilder,char value[]並不是final的

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

    /** Cache the hash code for the string */
    private int hash; // Default to 0

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -6849794470754667710L;
}

 

Why string objects are immutable in java?

Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

因爲Java使用字符串文字的概念(這個我覺得翻譯難以理解,所以google的,其餘的我都是自己翻譯的),假設又5個引用都是依賴於一個字符串對象"scchin" ,如果一個變化了,那麼所有的都會被改變,所以字符串設計爲不可變的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章