Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using == when comparing objects

Tags:

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()?

like image 441
KWJ2104 Avatar asked Dec 01 '22 23:12

KWJ2104


1 Answers

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.

like image 156
Greg Hewgill Avatar answered Dec 16 '22 23:12

Greg Hewgill