Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `==` sometimes work for Strings? [duplicate]

Consider this piece of code:

String baz = "Hello";
String foo = "Hello";
return foo.equals(baz); // Returns true as expected
return(baz == foo); // Also returns true!

Why does the == operator also return true in this case? It should be comparing the locations of the objects themselves, not their values.

I'm assuming that Java does some sort of internal work and determines these two are of type String (or Integer, etc.) so it implicitly calls the .equals() method.

I'm curious to know exactly how this is done (ie. what goes on in the background), and why this is done, what if I actually wanted to test their location in memory?

like image 513
Tiberiu Avatar asked Feb 12 '23 21:02

Tiberiu


1 Answers

return(baz == foo) is also returning true because all literal strings are interned in Java. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

So in short due to use of String intern pool for your case return(baz == foo) is behaving same as return(baz.equals(foo))

Read more about String literals in Java Specs

like image 196
anubhava Avatar answered Feb 14 '23 11:02

anubhava