Reputation: 31
In other words, if I have two variables:
String s;
String t;
Such that s == t
, then is s.equals(t)
guaranteed to return true?
I thought the answer to this was obviously yes, but it's on a practice exam provided by my professor for an introductory programming class final, and he says that is is not. Thoughts?
I realized that they could be null and therefore would referentially be equal, but you would not be able to call .equals
on them.
Upvotes: 1
Views: 1171
Reputation: 741
No, It does not imply the same.
s1==s2
will return whether or not references on s1
and s2
on String pool are same or not, not their contents.
While s1.equals(s2)
will check for the contents of String s1
and s2
.
Upvotes: 0
Reputation: 6780
==
means that the pointers to two objects are the same. That means the objects are contained in the same memory location. If that's true, they are the same object and must hold the same value, so .equals()
will be true as well.
Note that the opposite is not true - .equals()
being true does not gurantee that ==
will be true.
The only exceptions would be if you overrode the .equals()
method to always return false, or if both objects were null
.
Upvotes: 1