Witscale Test Center

13.3 The java.lang.String class > 13.3.4 Methods on String objects that appears to be changing it.


13.3.4 Methods on String objects that appears to be changing it.

By now you must be rock sure that string objects can never be changed. However there are many methods like concat() in String class, that could mislead you to believe that the underlying string object is actually changing. Let us consider those methods in an example, to clear out any confusion that may be left. In the following code, the methods replace() and toUpperCase() are used.

 

String message = new String("Hello");                         

message = message.concat(" World");                           #1

System.out.println(message); #2    

message.replace('o','u'); #3

System.out.println(message);                                  #2

message.toLowerCase(); #3

System.out.println(message); #2

message = message.toUpperCase(); #1

System.out.println(message); #4

 

(annotation)<#1 create a new String and assigns to the message>

(annotation)<#2 prints “Hello World”>

 (annotation)<#3 create a new string. No assignment hence it is lost>

(annotation)<#4 prints “HELLO WORLD”>

 

The calls replace(), toLowerCase() and toUpperCase() will all create new strings. If the new strings are assigned to some referenced, they are saved. Otherwise, they are immediately lost (and can be garbage collected later). Figure 13.9 illustrates the memory model after this code is executed.

 


 

Figure 13.9 Many new strings are created and immediately lost when manipulating methods are invoked on a string.

 

Figure shows many lost string objects. The new string objects created during the calls replace() and toLowerCase() are lost as their reference is not stored in any reference variable. Note that all the string objects are immutable (including the lost strings). Which string will be printed when we print the string reference message depends on which one it is pointing in the memory at that time.