-3

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.

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Artmal
  • 348
  • 2
  • 4
  • 16
  • [This answer](http://stackoverflow.com/a/40480291/) (to a slightly different question) explains everything you asked about. – Dawood ibn Kareem Nov 21 '16 at 09:37
  • I assume you understand that `str1 == str2` would return false; then, given that `str1` is assigned a string literal value, [the Javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern()) describes that `str.intern() == str1`. Hence, `str1.intern() == str2` is the same as `str1 == str2`, hence it is false. – Andy Turner Nov 21 '16 at 09:39

3 Answers3

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

In the above case you are comparing reference of interned String "Apple" with that of reference of another String which is on the heap (but with the same value). So, the result is "false".

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

In the above case, you are comparing a reference of String constants pool to a reference got by trying to add "Apple" to the String constants pool. SInce, "Apple" is already in the first line, this interning will return the object pointed to by str1. Hence you get true.

PS : This behavior is described in the javadoc

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

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...

therefore

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...

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

String.intern() method is used to create an exact copy of heap String object in String constant pool. The String objects in the String constant pool are automatically interned but String objects in heap are not

System.out.println(firstString.intern() == secondString);//false because it will fetch exact copy of the string compare in string

System.out.println(firstString == secondString.intern());//True because it will compare firstString with fetch the second String it will check heap or not
Nishant123
  • 1,968
  • 2
  • 26
  • 44