How to correctly use == and equals in Java?
In Java, both == and equals are methods used to compare objects, but they serve different purposes and behave differently.
- Operator:
- For primitive data types, the comparison is based on whether the values are equal.
- For reference data types, the comparison is based on whether the object references are equal, i.e., whether they point to the same memory address.
- For example:
- int a = 5, b = 5;
System.out.println(a == b); // prints trueString str1 = “hello”;
String str2 = “hello”;
String str3 = new String(“hello”);
System.out.println(str1 == str2); // prints true
System.out.println(str1 == str3); // prints false - equals() method:
- For primitive data types, the equals() method has not been overridden and still uses == for comparison.
- By default, for reference data types, the equals() method is the same as ==, comparing if the references are equal.
- Usually, we need to override the equals() method to customize the logic for comparing objects. Overriding the equals() method must meet the following conditions:
Reflexivity: For any non-null reference x, x.equals(x) should return true.
Symmetry: For any non-null references x and y, if x.equals(y) returns true, then y.equals(x) should also return true.
Transitivity: For any non-null references x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should also return true.
Consistency: For any non-null references x and y, if the information in the objects has not been modified, multiple calls to x.equals(y) should return the same result.
For any non-null reference x, x.equals(null) should return false. - For example,
- The Person class defines a method to check if two Person objects are equal based on their name and age.
- Example of use:
- Person person1 = new Person(“Alice”, 20);
Person person2 = new Person(“Alice”, 20);
Person person3 = new Person(“Bob”, 25);System.out.println(person1.equals(person2)); // Output: true
System.out.println(person1.equals(person3)); // Output: false
In conclusion:
- It is used to compare the values of primitive data types and to check if the references of reference data types are equal.
- The `equals()` method is used to compare the values of reference data types to see if they are equal, and it needs to be overridden based on specific business logic.