Consider the following example.
String str = new String();
str = \"Hello\";
System.out.println(str); //Prints Hello
str = \"Help!\";
System.out.println(s
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.