equals() Method In Java
equals() method is a public member of java.lang.Object class. As all classes in java extend Object class by default, this method is available in all classes you create in java. The default version of equals() method does the same thing as “==” operator i.e comparing the two objects based on their location in the memory. But, it is always recommended to override the equals() method so that it performs the comparison of two objects based on their content or based on any business logic. That means, if two objects satisfy the business logic, then calling equals method on those objects should return true, irrespective of their location in the memory.
== Operator In Java
“==” operator is a binary operator in java which compares the two objects based on their location in the memory. That means if two reference variables are pointing to same object in the memory then applying “==” operator on those reference variables will return true. You can apply “==” operator to both primitive types as well as derived types. But, it is best suitable for primitive types.
== operator vs equals () method
|Equal (==) operator
|It can be used to compare both primitive values, and objects.
|It can be used for comparing objects only. It can’t be used for primitive values.
|It compares primitives based on their values, and objects based on their reference.
|It compares objects either with their reference or with their state, it depends upon on equals() method implementation.
|The equal (==) operator can’t compare incompatible objects, the compiler throws the compile-time error.
|The equals() method can compare incompatible objects & in this case, it always returns “false”.
|It is an operator and can’t be overridden.
|It is a method and can be overridden.
What you need to know about == operator and equals () method
- == operator is a binary operator in java whereas equals () is a public method of java.lang.Object class.
- Equality operator can be used to compare primitives as well as objects. Equals method can only be used with objects.
- Equality operator compares the object references when two objects are compared using equality operator. Equals method when overridden can do content comparison of two objects.
- You can’t override the “==” operator. It behaves same for all objects.You can override the equals method according to your business requirements.
- == Operator is is best suitable for primitive types whereas equals () method is best suitable for derived types.