Immutability of Strings in Java

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

    The object that str references can change, but the actual String objects themselves cannot.

    The String objects containing the string "Hello" and "Help!" cannot change their values, hence they are immutable.

    The immutability of String objects does not mean that the references pointing to the object cannot change.

    One way that one can prevent the str reference from changing is to declare it as final:

    final String STR = "Hello";
    

    Now, trying to assign another String to STR will cause a compile error.

提交回复
热议问题