Showing posts with label intern(). Show all posts
Showing posts with label intern(). Show all posts

Wednesday, April 25, 2012

Use of intern() method in String class

intern() method is present in String class. 

Lets take an example 
String str = new String("abc");
String strComp = "abc";

str.equals(strComp) returns true, because equals method will checks the contents of strings.

But, (str == strComp) returns false, because it will compare the references.
In this case, because we used the new keyword, Java will create a new String object in normal (nonpool) memory, and str will refer to it. In addition, the literal "abc" will be placed in the pool.

If we use intern() 
str = str.intern();

Now the reference of 'str' will change from object outside the string pool to "abc" literal present inside string pool.

After execution (str == strComp) will return TRUE.