|
You can re-assign a reference to a string object to another string object. However, that does not mean you have modified the original string object. In the following example, the string reference str1 is made to point the string object reference by str2.
String str1 = new String("Hello");
String str2 = new String("World");
str1 = str2;
System.out.println(str1); // prints "World"
Now when you print str1, “World” will be printed. Does that mean the string object created at first line (containing characters Hello) is modified to a new string object (containing characters World)? No, the string object created on first line is still immutable and still contains the sequence of characters Hello. But now it does not have any reference. Figure 13.8 illustrates the memory model after this code is executed.
![]() |
The string object containing Hello is lost as it does not have any reference. However, it remains unchanged throughout its life. That means it contains the exact same sequence of characters where were assigned when it was created for the first time. Thus the string reference are mutable (changeable) but string objects are immutable (unchangeable). Note that whenever you modify the contents of a string object, a new string object is created. The original string object remains the same.
|
|
The exam may have questions asking which of the given options will modify the string object. Be careful while answering such question and remember that Java strings are unchangeable. |