Immutability of Strings in Java

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

    String is immutable. Which means that we can only change the reference.


    String a = "a";
    System.out.println("String a is referencing to "+a); // Output: a
    
    a.concat("b");
    System.out.println("String a is referencing to "+a); // Output: a
    
    a = a.concat("b");
    System.out.println("String a has created a new reference and is now referencing to "+a); // Output: ab
    

提交回复
热议问题