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
.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With