Java – Using ‘==’ When Comparing Objects

java

Recently in a job interview I was asked this following question (for Java):

Given:

String s1 = "abc";
String s2 = "abc";

What is the return value of

(s1 == s2)

I answered with it would return false because they are two different objects and == is a memory address comparison rather than a value comparison, and that one would need to use .equals() to compare String objects. I was however told that although the .equals(0 methodology was right, the statement nonetheless returns true. I was wondering if someone could explain this to me as to why it is true but why we are still taught in school to use equals()?

Best Answer

String constants are interned by your JVM (this is required by the spec as per here):

All literal strings and string-valued constant expressions are interned. String literals are defined in ยง3.10.5 of the Java Language Specification

This means that the compiler has already created an object representing the string "abc", and sets both s1 and s2 to point to the same interned object.

Related Question