Possible Duplicate:
Java String.equals versus ==
Is it possible to compare Java Strings using == operator?
Why do I often see, that equals() method is used instead?
Is it because when comparing with literal Strings (like "Hello") using == doesn't imply calling equals()?
== operator checks the bit pattern of objects rather than the contents of those objects, but equals function compare the contents of objects.
System.out.println(str1==str2); will return false because str1 and str2 are different object created with "new" . System.out.println(str1.equals(str2)) will return true because equals() checks for contents of object.
In Java, you cannot overload operators. The
==
operator does identity equality. Theequals(...)
method, on the other hand can be be overridden to do type-specific comparisons.Here's a code snippet to demonstrate:
The one complication is with
equals(...)
you need to care about null, too. So the correct null-safe idiom is:This is a loop you don't have to jump through in say C#
To expand on @amit's answer, the == operator should only be used on value types (int, double, etc.) A String is a reference type and should therefore be compared with the .equals() method. Using the == operator on a reference type checks for reference equality in java (meaning both object references are pointing to the same memory location.)
No, it's not possible, because with == you compare object references and not the content of the string (for which you need to use equals).
Operator == compares for string object references ,whereas String.equals method checks for both object references + object values . Moreover , String.equals method inturn uses == operator inside its implementation.
==
checks if the two objects refer to the same instance of an object, whereasequals()
checks whether the two objects are actually equivalent even if they're not the same instance.