How to use == operator and equals() method correctly in Java
In this post, we will see how to use the == operator and equals() method correctly in Java.
1. Overview of == operator and equals() method
The == is a relational operator in Java that is used to compare primitive types such as int, double, char, float, etc. We should not use it to compare two object references since for any non-null reference values x and y, x == y returns true only when x and y refer to the same object.
The equals() method in the Object class is used to compare objects. It behaves similarly to the == operator if not overridden by a class. Every class should override the equals() method of the Object class and specify the equivalence relation on objects. The equivalence relation should be such that equals() methods evaluate the comparison of values in the objects irrespective of the two objects refer to the same instance or not. Since equal objects must have equal hash codes, it is necessary to override the hashCode() method.
2. How to use the == operator and equals() method correctly in Java?
The general rule of thumb is to use the == operator when we want to compare primitive types or references of objects, and use the equals() method when we want to compare the contents or states of objects. However, there are some exceptions and caveats that we should be aware of when using these operators and methods. Here are some tips and best practices that we should follow:
1. Using with complex expressions
Always use parentheses when using the == operator and equals() method with complex expressions or logical operators. This will avoid any confusion or ambiguity about the order of evaluation or precedence. For example:
|
1 2 3 4 5 6 7 8 9 |
// Bad practice: no parentheses if (x + y == z + w && a.equals(b)) { // do something } // Good practice: use parentheses if ((x + y) == (z + w) && a.equals(b)) { // do something } |
2. Using with Strings
Always use equals() method when comparing strings or comparing other objects that override this method. Do not use == operator for comparing strings or other objects that override this method unless we are sure that we want to compare their references. This will avoid any unexpected or incorrect results due to different memory locations or implementations. For example:
|
1 2 3 4 5 6 7 8 9 |
// Bad practice: use `==` operator for comparing strings if (s1 == s2) { // do something } // Good practice: use equals() method for comparing strings if (s1.equals(s2)) { // do something } |
3. Using with possible null objects
Always check for null values before using the equals() method. If we call the equals() method on a null reference, we will get a NullPointerException, which is a runtime exception that can crash our program. To avoid this, we should always check if the object is null before calling the equals() method. For example:
|
1 2 3 4 5 6 7 8 9 |
// Bad practice: call equals() method on a null reference if (s1.equals(s2)) { // do something } // Good practice: check for null values before calling equals() method if (s1 != null && s1.equals(s2)) { // do something } |
4. Using with Objects
Always override the equals() method and the hashCode() method together when creating our own classes. The hashCode() method is another method that is defined in the Object class, and it returns an integer value that represents the hash code of an object. The hash code is used by some data structures and algorithms, such as hash tables and sets, to store and retrieve objects efficiently. The contract between the equals() method and the hashCode() method is that if two objects are equal according to the equals() method, they must have the same hash code according to the hashCode() method. Therefore, if we override the equals() method in our class, we should also override the hashCode() method to ensure consistency and correctness.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
// Example class that overrides equals() and hashCode() class Student { private int id; private String name; public Student(int id, String name) { this.id = id; this.name = name; } // Override equals() method to compare two students based on their id and name @Override public boolean equals(Object obj) { // Check if obj is null or not an instance of Student if (!(obj instanceof Student)) { return false; } // Check if obj is the same reference as this if (obj == this) { return true; } // Cast obj to Student and compare their fields Student other = (Student) obj; return this.id == other.id && this.name.equals(other.name); } // Override hashCode() method to return a hash code based on the id and name @Override public int hashCode() { // Use a prime number and the XOR operator to combine the hash codes of the fields int prime = 31; int result = prime + id; result = prime * result + name.hashCode(); return result; } } class Main { public static void main(String[] args) { Student s1 = new Student(101, "David"); Student s2 = new Student(101, "David"); System.out.println(s1.equals(s2)); // true } } |
That’s all about using the == operator and equals() method correctly in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)