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?