Today's Question:  What does your personal desk look like?        GIVE A SHOUT

String intern in Java

  sonic0002        2016-04-10 03:35:25       3,882        0    

In Java, == is used to compare whether two objects have the same memory location, equals() is usually used to compare whether two objects have the same time and the same state.  When comparing two strings, normally we just want to know whether they have same content, so we can choose equals(). But since String comparison is so frequently needed, Java has worked on the String class to make == workable when comparing two String literals.

The String class maintains a pool of empty string literals initially. Then when a new string is created, this new string will checked against the pool and if its content is not present, the content will be added to the pool, otherwise, the object in the pool will be returned. Normally, when creating string literals, the strings are interned which mean all Strings with the same content will have the same content and == will return true on their comparison.  For example, if we create below two Strings and compare them, the result will be true.

String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1 == s2);

We no need to call equals() to compare them. What if we create below two strings with the constructor calls?

String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1 == s2);

The result will be false because each new call will create new reference to the object created. Since the two references are not the same, the == comparison will return false. In order to compare these two objects with ==, Java String provides a method named intern() which can return a canonical representation for the string object.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.  

Hence if the above two call is written as below, then the result will be true.

String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1.intern() == s2.intern());

These intern() calls will return the String reference to the same object if they have the same content.

JAVA  STRING 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  0 COMMENT


No comment for this article.