Вопрос

class helloworld
{
   public static void main(String args[]) {
       String str1="hello";
       String str2="world";
       String str=str1+str2;
       str.intern();
       System.out.println(str=="helloworld");
   }
}  

o/p: false

After Executing the program it produces false as output.if equals() is used instead of "==" it returns true.why so?

2.In this case after changing classname it produces true as output.

class main
{
   public static void main(String args[]) {
       String str1="hello";
       String str2="world";
       String str=str1+str2;
       str.intern();
       System.out.println(str=="helloworld");
  }
} 

o/p:true

Why the contradiction occurs b/w interned string comparison using "==" with classname (in case of comparison string name is used as classname)?

Это было полезно?

Решение

The reason is that in the first example, the string "helloworld" is already in the string pool, on account of its being the name of the class. So interning it doesn't add anything to the string pool. So str won't be the interned value, and the comparison will be false.

In the second example, str.intern() actually adds str to the string pool, because "helloworld" is not already there. Then, when the "helloworld" literal is encountered, the string object that's actually used is the one that's in the string pool. That's just str, so the comparison will be true.

Другие советы

String is immutable. You must use the return value of str.intern(). Just calling str.intern() and ignoring the return value does nothing.

str = str.intern();

Supplementing answers, here a nice articles about intern()

English: https://weblogs.java.net/blog/2006/06/26/all-about-intern

Russian: http://habrahabr.ru/post/79913/

String in an immutable Object. And as of intern() function as per javadoc

When the intern method is invoked, if the pool already contains a
string equal to this <code>String</code> object as determined by
the {@link #equals(Object)} method, then the string from the pool is
returned. Otherwise, this <code>String</code> object is added to the
pool and a reference to this <code>String</code> object is returned.

So you must assign the return value Eg string = string.intern();

As for your output it should be true irrespective of your class name because as mentioned above it has nothing to do with calling intern().

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top