What is String intern() method ?

Basically, it internalizes strings such that for any two strings, s1.intern() == s2.intern() if and only if s1.equals(s2). In other words, it makes sure that the returned string reference points to the single, canonical version of that string of characters. It does this by managing a pool of unique string values.
typically, we can't use the == operator to compare string values because the == operator is just comparing the values of references to those strings rather than the strings' values. But, for internalized strings, since we know that the value of the reference will always be to the unique, canonical version of the string, we can use the == operator.
Therefore, the primary benefit in this case is that using the == operator for internalized strings is a lot faster than use the equals() method. So, use the intern() method if you're going to be comparing strings more than a time or three.
Example:
public class demo {
 public static void main(String[] args) { 
     String str1 = "bhabani";
     String str = new String("bhabani");
     String str2 = str.intern();
     boolean a= str1 == str;
     boolean b= str1 == str2;
     System.out.println(a+"-"+b);
 }
}
Result:
false-true
When str.intern() is called then it refers to str1(in pool). So str1 and str referances become same.

No comments:

Post a Comment