Possible Duplicate:
Difference Between Equals and ==
For example, if I have
MyClass foo = new MyClass();
MyClass bar = new MyClass();
if (foo == bar) {
// do something
}
if (foo < bar) {
// do something
}
if (foo > bar) {
// do something
}
how do foo and bar get compared? Does Java look for .compareTo() methods to be implemented for MyClass? Does Java compare the actual binary structure of the objects bit for bit in memory?
Very simply the arithmetic comparison operators
==and!=compare the object references, or memory addresses of the objects.>, and<and related operators can’t be used with objects.So
==,!=is useful only if you want to determine whether two different variables point to the same object.As an example, this is useful in an event handler: if you have one event handler tied to e.g. multiple buttons, you’ll need to determine in the handler which button has been pressed. In this case, you can use
==.Object comparison of the type that you’re asking about is captured using methods like
.equals, or special purpose methods likeString.compareTo.It’s worth noting that the default
Object.equalsmethod is equivalent to==: it compares object references; this is covered in the docs. Most classes built into Java overrideequalswith their own implementation: for example,Stringoverridesequalsto compare the characters one at a time. To get a more specific/useful implementation of.equalsfor your own objects, you’ll need to override.equalswith a more specific implementation.