Immutability of Strings in Java

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

    Immutability implies that the value of an instantiated object cannot change, you can never turn "Hello" into "Help!".

    The variable str is a reference to an object, when you assign a new value to str you aren't changing the value of the object it references, you are referencing a different object.

提交回复
热议问题