Witscale Test Center

13.3 The java.lang.String class > 13.3.3 String objects created as literals are immutable too.


13.3.3 String objects created as literals are immutable too.

String literals are also string objects. Only they are created a bit different. String literals are created on literal pool whereas the string objects are created on memory heap. In case of string objects, always a new string object is created when you use new keyword. In case of literals, if there is already a literal with a certain sequence of characters (in the literal pool), then new string literal is not created (see chapter 8, Operators for details of string creation). However, this optimization at the time of creation does not change any other thing about the string literals. String literals are also the string objects and like string objects, the string literals are immutable too. For example, the following code will not change the string literal created on line 1.

 

String str = "Hello";

str.concat(" World");

System.out.println(str); // prints "Hello"

 

str.concat(“ World”) will create a new string object and returns its reference. But since we are not storing this reference in any reference variable, this new string object “Hello World” will be lost and cannot be used. If you want to use it, you can store its reference as:

 

String str = "Hello";

String anotherString = str.concat(" World");

System.out.println(anotherString); // prints "Hello World"

 

Remember that the string literal “Hello” created on the first line remains unchanged. In fact, the string object pointed by anotherString also remains unchanged after it is created on second line.

 

When you create a string object using the new keyword, often you are creating two string objects. For example in String str = new String(“Hello”); two string objects are created. The first one is the literal between double quotes “Hello” which is passed to the String constructor. This string object is created on literal pool. The second string object is created on the heap using the new keyword. After execution, the string object created on heap will have a reference str. However, the string on literal pool will not have any reference and hence it will be considered as lost.