Consider the following Java program:
The reason for printing “Not Equal” is simple: when we compare c1 and c2, it is checked whether both c1 and c2 refer to same object or not (object variables are always references in Java). c1 and c2 refer to two different objects, hence the value (c1 == c2) is false. If we create another reference say c3 like following, then (c1 == c3) will give true.
So, how do we check for equality of values inside the objects? All classes in Java inherit from the Object class, directly or indirectly (See point 1 of this). The Object class has some basic methods like clone(), toString(), equals(),.. etc. We can override the equals method in our class to check whether two objects have same data or not.
As a side note, when we override equals(), it is recommended to also override the hashCode() method. If we don’t do so, equal objects may get different hash-values; and hash based collections, including HashMap, HashSet, and Hashtable do not work properly (see this for more details). We will be coverig more about hashCode() in a separate post.
Effective Java Second Edition
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Difference between Method Overloading and Method Overriding in Java
- Exception Handling with Method Overriding in Java
- Overriding toString() in Java
- Overriding in Java
- Overriding methods from different packages in Java
- Overriding of Thread class start() method
- Method Overriding with Access Modifier
- Method Class | equals() Method in Java
- Java.util.Arrays.equals() in Java with Examples
- Difference between == and .equals() method in Java
- Calendar.equals() method in Java
- Java Long equals() method with Examples
- Character.equals() method in Java with examples
- Double.equals() Method in Java with Examples
- MathContext equals() Method in Java
- BigDecimal equals() Method in Java
- EnumMap equals() Method in Java with Examples
- IdentityHashMap equals() Method in Java
- GregorianCalendar equals() Method in Java
- BigInteger equals() Method in Java