5 Difference Between == Operator And equals() Method in Java
Table of Contents
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.
Also Read: Difference Between Abstract And Interface In Java
== operator vs equals () method
Equal (==) operator | equals() method |
---|---|
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
ncG1vNJzZmiumauupbXFn5yrnZ6YsrR6wqikaJyZm7OmvsSnmp5lkprBuLHEp2SoqJWnrrW70WaYp5xdmr62rcusZKadpJ28pXnIp2SjmaaWfA%3D%3D