Immutability of Strings in Java

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

    String in Java in Immutable and Final just mean it can't be changed or modified:

    Case 1:

    class TestClass{  
     public static void main(String args[]){  
       String str = "ABC";  
       str.concat("DEF");  
       System.out.println(str);  
     }  
    } 
    

    Output: ABC

    Reason: The object reference str is not changed in fact a new object "DEF" is created which is in the pool and have no reference at all (i.e lost).

    Case 2:

    class TestClass{  
     public static void main(String args[]){  
       String str="ABC";  
       str=str.concat("DEF");  
       System.out.println(str);  
     }  
    }  
    

    Output: ABCDEF

    Reason: In this case str is now referring to a new object "ABCDEF" hence it prints ABCDEF i.e. previous str object "ABC" is lost in pool with no reference.

提交回复
热议问题