When should one compare String
s as objects and when should one use their equals
method? To make sure, I always use equals
, but that doesn't seem very efficient. In what situations can I be certain that string1 == string2
is a safe to use?
Thanks!
From what I know of Java,
string1==string2
will only be true if the references to those objects are the same. Take a look at the following caseYou can only use the
==
for comparison if you are sure the objects are the same.For example, this could occur if you had a final static String variable. You could be certain that a comparison would be between the same object.
Stick with the
equals
for string comparison.You should almost always use
equals
. You can be certain thatstring1 == string2
will work if:It really doesn't happen very often, in my experience.