Consider the following example.
String str = new String();
str = \"Hello\";
System.out.println(str); //Prints Hello
str = \"Help!\";
System.out.println(s
I would explain it with simple example
consider any character array : e.g. char a[]={'h','e','l','l','o'}; and a string : String s="hello";
on character array we can perform operations like printing only last three letters using iterating the array; but in string we have to make new String object and copy required substring and its address will be in new string object.
e.g.
***String s="hello";
String s2=s.substrig(0,3);***
so s2 will have "hel";
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.