-3

I wanted to ask about String and Reference variable, String name = "John" String str= "John" In the video it says that it will refer to the value "John" instead of creating another value "John". If this was the case then if we compare (name == str) why would it give False? Does variable name and Str refer to the same address in the Heap?

Justin
  • 5

2 Answers2

0

It is called String interning. If the constant (in this case "John") is a compile time constant, then the compiler will use "John".intern() when compiling and it will go to the string "pool" hence the 2 "interned" string reference will be the same therefore using "==" will return true. JVM spec page 359:

If the method String.intern has previously been invoked on an instance of class String containing a sequence of Unicode code points identical to that given by the CONSTANT_String_info structure, then the string constant is a reference to that same instance of class String

Bela Vizer
  • 2,527
  • 22
  • 26
-1

The == operator is used for checking the reference of both the string objects in Java.

https://dzone.com/articles/how-do-i-compare-strings-in-java (search for Problems Using the == Operator for String Comparison)

Anup
  • 23
  • 8