Use of intern() in java

First of all, type the below code snippet and save it as Test.java , the compile and run it. and then view the description below code is given.

public class Test{
public static void main(String[] args){
String s1 = "Java";
String s2 = new String("Java");
System.out.println(s1==s2);
s2=s2.intern();
System.out.println(s1==s2);
}
}

When the intern() method is invoked on a String, a lookup is performed on a table of interned Strings. If a String object with the same content is already in the table, a reference to the String in the table is returned. 
Otherwise, the String is added to the table and a reference to it is returned. 
The result is that after interning, all Strings with the same content will point to the same object. 
This saves space, and also allows the Strings to be compared using the == operator, which is much faster than comparison with the equals(Object) method.
So in simple way this function my useful in development.

No comments:

Post a Comment