When you compare objects in Java you should prefer the
== in general. The reason is that you get reference equality (like with
==) by default but you are able to change that behaviour. You can override
equals() (DO NOT FORGET TO OVERRIDE
hashCode() too because otherwise you will break the general class contract) to reflect logical equality which is often what you want, e.g when comparing some string constant with user input.
With primitive types like
int you are more or less limited to
== which is fine for those immutable value types.
But what is the right thing to to with the
enum type introduced in Java 5?
Since enums look like a class with methods, fields and the like you might want to use
equals() instead of
==. Now this is a special case where using reference equality is actually safer and thus better than logical equality.
Above (please mind the stupid example) we can see that comparing the
EState enum with an
ILamp using equals() is accepted perfectly by the compiler even though the condition never can be true in practice. Using
== the compiler screams and tells us that we are comparing apples with oranges.