Immutability of Strings in Java

后端 未结 26 2329
不思量自难忘°
不思量自难忘° 2020-11-21 06:33

Consider the following example.

String str = new String();

str  = \"Hello\";
System.out.println(str);  //Prints Hello

str = \"Help!\";
System.out.println(s         


        
26条回答
  •  感情败类
    2020-11-21 07:32

    String class is immutable, and you can not change value of immutable object. But in case of String, if you change the value of string than it will create new string in string pool and than your string reference to that value not the older one. so by this way string is immutable. Lets take your example,

    String str = "Mississippi";  
    System.out.println(str); // prints Mississippi 
    

    it will create one string "Mississippi" and will add it to String pool so now str is pointing to Mississippi.

    str = str.replace("i", "!");  
    System.out.println(str); // prints M!ss!ss!pp! 
    

    But after above operation, one another string will be created "M!ss!ss!pp!" and it will be add to String pool. and now str is pointing to M!ss!ss!pp!, not Mississippi.

    so by this way when you will alter value of string object it will create one more object and will add it to string pool.

    Lets have one more example

    String s1 = "Hello"; 
    String s2 = "World"; 
    String s = s1 + s2;
    

    this above three line will add three objects of string to string pool.
    1) Hello
    2) World
    3) HelloWorld

提交回复
热议问题