Immutability of Strings in Java

后端 未结 26 2317
不思量自难忘°
不思量自难忘° 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

    0 讨论(0)
  • 2020-11-21 07:33

    The Object string - methods itself is made to be "immutable". This action produces no changes: "letters.replace("bbb", "aaa");"

    But assigning data does cause changes to the Strings content to change:

        letters = "aaa";
        letters=null;
        System.out.println(letters);
        System.out.println(oB.hashCode());
        System.out.println(letters);
        letters = "bbbaaa";
        System.out.println(oB.hashCode());
        System.out.println(letters);
    

    //The hashcode of the string Object doesn't change.

    0 讨论(0)
  • 2020-11-21 07:34

    Lets break it into some parts

    String s1 = "hello";
    

    This Statement creates string containing hello and occupy space in memory i.e. in Constant String Pool and and assigned it to reference object s1

    String s2 = s1;
    

    This statement assigns the same string hello to new reference s2

             __________
            |          |
    s1 ---->|  hello   |<----- s2
            |__________| 
    

    Both references are pointing to the same string so output the same value as follows.

    out.println(s1);    // o/p: hello
    out.println(s2);    // o/p: hello
    

    Though String is immutable, assignment can be possible so the s1 will now refer to new value stack.

    s1 = "stack";    
             __________
            |          |
    s1 ---->|  stack   |
            |__________|
    

    But what about s2 object which is pointing to hello it will be as it is.

             __________
            |          |
    s2 ---->|  hello   |
            |__________|
    
    out.println(s1);    // o/p: stack
    out.println(s2);    // o/p: hello
    

    Since String is immutable Java Virtual Machine won't allow us to modify string s1 by its method. It will create all new String object in pool as follows.

    s1.concat(" overflow");
    
                     ___________________
                    |                   |
    s1.concat ----> |  stack overflow   |
                    |___________________|
    
    out.println(s1);    // o/p: stack
    out.println(s2);    // o/p: hello
    out.println(s1.concat); // o/p: stack overflow
    

    Note if String would be mutable then the output would have been

    out.println(s1);    // o/p: stack overflow
    

    Now you might be surprised why String has such methods like concat() to modify. Following snippet will clear your confusion.

    s1 = s1.concat(" overflow");
    

    Here we are assigning modified value of string back to s1 reference.

             ___________________
            |                   |
    s1 ---->|  stack overflow   |
            |___________________|
    
    
    out.println(s1);    // o/p: stack overflow
    out.println(s2);    // o/p: hello
    

    That's why Java decided String to be a final class Otherwise anyone can modify and change the value of string. Hope this will help little bit.

    0 讨论(0)
  • 2020-11-21 07:34

    Immutability I can say is that you cannot change the String itself. Suppose you have String x, the value of which is "abc". Now you cannot change the String, that is, you cannot change any character/s in "abc".

    If you have to change any character/s in the String, you can use a character array and mutate it or use StringBuilder.

    String x = "abc";
    x = "pot";
    x = x + "hj";
    x = x.substring(3);
    System.out.println(x);
    
    char x1[] = x.toCharArray();
    x1[0] = 's';
    String y = new String(x1);
    System.out.println(y);
    

    Output:

    hj
    sj
    
    0 讨论(0)
  • 2020-11-21 07:35

    The String will not change, the reference to it will. You are confusing immutability with the concept of final fields. If a field is declared as final, once it has been assigned, it cannot be reassigned.

    0 讨论(0)
  • 2020-11-21 07:37

    Regarding the replace part of your question, try this:

    String str = "Mississippi"; 
    System.out.println(str); //Prints Mississippi 
    
    String other = str.replace("i", "!"); 
    System.out.println(str); //still prints Mississippi 
    System.out.println(other);  // prints M!ss!ss!pp!
    
    0 讨论(0)
提交回复
热议问题