Immutable String and Interned Strings

A String object is immutable; its contents cannot be changed. Does the following code change the contents of the string?
String s = "Java"; s = "HTML";
The answer is no. The first statement creates a String object with the content “Java” and assigns its reference to s. The second statement creates a new String object with the con- tent “HTML” and assigns its reference to s. The first String object still exists after the assignment, but it can no longer be accessed, because variable s now points to the new object, as shown in Figure


Since strings are immutable and are ubiquitous in programming, the JVM uses a unique instance for string literals with the same character sequence in order to improve efficiency and save memory. Such an instance is called interned. For example, the following statements:

class immutable
{
public static void main(String[] arg)
{
String str1 = "Welcome to Smartprogrammeron.blogspot.in";
String str2 = new String("Welcome to Smartprogrammeron.blogspot.in");
String str3 = "Welcome to Smartprogrammeron.blogspot.in";
System.out.println("strt1 == str2 is " + (str1 == str2));
System.out.println("str1 == str3 is " + (str1 == str3));
}
}


In the preceding statements, strt1 and str3 refer to the same interned string “Welcome to Smartprogrammeron.blogspot.in”, therefore strt1 == str3 is true. However, strt1 == str2 is false, because strt1 and str2 are two different string objects, even though they have the same contents.

Popular posts from this blog

Shutdown Pc

Ellipse using OpenGl

String Comparisons