The obvious answer to the question has already been given, but here is a warning that is not a direct answer: obj.equals
can also fail if obj is null. So you'll often have to use code like this:
if(mystr1 != null && mystr1.equals(mystr2))
because this
if(mystr1.equals(mystr2))
would fail with a NullPointerException if mystr1 is null.
Which is why, when the comparison string is a known constant, the following syntax is often used:
if("ABCDEF".equals(mystr1))
rather than
if(mystr1.equals("ABCDEF"))
For this reason, many libraries (like apache commons / lang ) provide utility functions that combine these checks:
// this is the definition of org.apache.commons.lang.StringUtils.equals(String, String)
public static boolean equals(String str1, String str2) {
return str1 == null ? str2 == null : str1.equals(str2);
}
// this is the definition of org.apache.commons.lang.ObjectUtils.equals(Object, Object)
public static boolean equals(Object object1, Object object2) {
if (object1 == object2) {
return true;
}
if ((object1 == null) || (object2 == null)) {
return false;
}
return object1.equals(object2);
}
Using these methods is usually safer than plain equals, unless you know for sure that one of the two objects is not null