Immutability of Strings in Java

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

    Or you can try:

    public class Tester
    {
    public static void main(String[] args)
    {
     String str = "Mississippi"; 
     System.out.println(str); // prints Mississippi 
     System.out.println(str.hashCode());
    
     str = str.replace("i", "!"); 
     System.out.println(str); // prints M!ss!ss!pp! 
     System.out.println(str.hashCode());
     }
     }
    

    This will show how the hashcode changes.

提交回复
热议问题