Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why intern method does not return equal String in java [duplicate]

Tags:

java

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.

like image 388
user3520698 Avatar asked Aug 16 '14 15:08

user3520698


1 Answers

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
}
like image 122
Mureinik Avatar answered Sep 29 '22 06:09

Mureinik