Immutability of Strings in Java

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

    Like Linus Tolvards said:

    Talk is cheap. Show me the code

    Take a look at this:

    public class Test{
        public static void main(String[] args){
    
            String a = "Mississippi";
            String b = "Mississippi";//String immutable property (same chars sequence), then same object
    
            String c = a.replace('i','I').replace('I','i');//This method creates a new String, then new object
            String d = b.replace('i','I').replace('I','i');//At this moment we have 3 String objects, a/b, c and d
    
            String e = a.replace('i','i');//If the arguments are the same, the object is not affected, then returns same object
    
            System.out.println( "a==b? " + (a==b) ); // Prints true, they are pointing to the same String object
    
            System.out.println( "a: " + a );
            System.out.println( "b: " + b );
    
            System.out.println( "c==d? " + (c==d) ); // Prints false, a new object was created on each one
    
            System.out.println( "c: " + c ); // Even the sequence of chars are the same, the object is different
            System.out.println( "d: " + d );
    
            System.out.println( "a==e? " + (a==e) ); // Same object, immutable property
        }
    }
    

    The output is

    a==b? true
    a: Mississippi
    b: Mississippi
    c==d? false
    c: Mississippi
    d: Mississippi
    a==e? true
    

    So, remember two things:

    • Strings are immutable until you apply a method that manipulates and creates a new one (c & d cases).
    • Replace method returns the same String object if both parameters are the same

提交回复
热议问题