Artmal Artmal - 5 months ago 31
Java Question

Comparing two equal Strings after intern() method

Javadoc says that if in the string pool there is an equal String that the intern() method will return the String.

public class Demo {
public static void main(String[] args) {
String str1 = "Apple";
String str2 = new String("Apple");

System.out.println(str1.intern() == str2); //false
System.out.println(str1 == str2.intern()); //true

I expected to get true in both cases.


Doing this str1.intern() is bringing nothing to your try... Since str1 is a literal string (it will be inmediatly placed in the string pool), and you are comparing it against the str2 which is allocated on the Heap...


System.out.println(str1.intern() == str2); 

will print false, you are comparing the reference of a string in the stirng pool vs a string on the heap...