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?
-
3Please show the code you executed that shows this behavior. – OldProgrammer Mar 20 '22 at 02:36
-
Try reading these answers https://stackoverflow.com/q/513832/217324 – Nathan Hughes Mar 20 '22 at 02:38
-
1"why would it give False?" It would not give `false`. Show the code demonstrating that it gives `false`. – Jeff Holt Mar 20 '22 at 02:44
2 Answers
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

- 2,527
- 22
- 26
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)

- 23
- 8