Java Reference
In-Depth Information
String Objects Are Immutable
String
objects are immutable. That is, you cannot modify the content of a
String
object. This leads to an advantage
that strings can be shared without worrying about them getting modified. For example, if you need two objects of
the
String
class with the identical content (the same sequence of characters), you can create one
String
object and
you can use its reference at both places. Sometimes the immutability of strings in Java is misunderstood, typically by
beginners. Consider the following piece of code:
String str;
str = new String("Just a string");
str = new String("Another string");
Here,
str
is a reference variable that can refer to any
String
object. In other words,
str
can be changed and it is
mutable. However, the
String
object, which
str
refers to, is always immutable. This scenario is depicted in Figure
11-1
and Figure
11-2
.
This is a String object, which is
immutable. You cannot change its
content.
Now, str is referring to a
String object in memory.
This is a reference variable and
can be changed.
str
str
Just a string
x
x
String str;
str = new String("Just a string");
Figure 11-1.
A String reference variable and a String object
Now, str is referring to another
string object in memory
This is the string object, which is
immutable. You cannot change
its content
str
Another string
x
str= new String("Another string");
Figure 11-2.
Assigning a different String object reference to a String variable