Immutability of Strings in Java

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

    Use:

    String s = new String("New String");
    s.concat(" Added String");
    System.out.println("String reference -----> "+s); // Output: String reference -----> New String
    

    If you see here I use the concat method to change the original string, that is, "New String" with a string " Added String", but still I got the output as previous, hence it proves that you can not change the reference of object of String class, but if you do this thing by StringBuilder class it will work. It is listed below.

    StringBuilder sb = new StringBuilder("New String");
    sb.append(" Added String");
    System.out.println("StringBuilder reference -----> "+sb);// Output: StringBuilder reference -----> New String Added String
    

提交回复
热议问题