5
public static void main (String[] args) {

    String s1 = new String("hello");
    String s2 = new String("hello");
    s1.intern();
    s2.intern();        
    System.out.println(s1 == s2); // why this returns false ?


}

as per my understanding, 1st call to intern method should have created a 'string intern pool' with a single string "hello". second call to intern method would have done nothing (as "hello" string is already present in pool). Now, when i say s1 == s2 i am expecting JVM to compare "hello" string from string intern pool and return true.

gkrls
  • 2,618
  • 2
  • 15
  • 29
user3520698
  • 77
  • 2
  • 9
  • Wow answers were ready, just waiting all for site to come back in write mode. – Braj Aug 16 '14 at 16:07
  • As you aren't comparing the value returned by String.intern(), your expectations of how this comparison should work are wholly lacking in basis. – user207421 Aug 16 '14 at 23:08
  • Just because it's a question about String.intern doesn't mean it's a dup. In this case the OP thought that intern had an effect on the string it was called on. The other question is a completely different question on String.intern. – aioobe Aug 17 '14 at 10:48

4 Answers4

4

You are just checking on the original strings that refer to different objects in the heap. You are not storing the returned value of String#intern() method.

It should be

String s1 = new String("hello");
String s2 = new String("hello");
String s11 = s1.intern();
String s22 = s2.intern();
System.out.println(s11 == s22); // returns true
Braj
  • 46,415
  • 5
  • 60
  • 76
4

The intern() method does not modify the string, it simply returns the corresponding string from the string pool. So, since you're not keeping the return values, your calls to intern() are meaningless. However, if you actually use them, you'll see that both point to exactly the same string:

public static void main (String[] args) {
    String s1 = new String("hello");
    String s2 = new String("hello");
    s1 = s1.intern();
    s2 = s2.intern();        
    System.out.println(s1 == s2); // will print true
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
3

String.intern returns a new interned string. To change s1 and s2 you do

s1 = s1.intern();
s2 = s2.intern();

s1 == s2 will then return true.

Martin C.
  • 12,140
  • 7
  • 40
  • 52
aioobe
  • 413,195
  • 112
  • 811
  • 826
1

Its actually string property that you need to assign the value after calling these method, Lets take an example even if:

String S1= "Hello";
S1.concat("World");

and if you print the value of S1 it will print only "Hello". but if you write like this:

S1=S1.concat(" World");

then it will print "Hello World".

Similarly you need to assign the value as:

s1=s1.intern();
s2=s2.intern();

and if you compare s1==s2 it will return true value but, Lets say:

String s3=s1.intern();
String s4=s2.intern();

and if you compare s3==s4 then its true but (s3==s1) and (s4==s2) are false.