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.

  1. Operator:
  2. For primitive data types, the comparison is based on whether the values are equal.
  3. 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.
  4. For example:
  5. int a = 5, b = 5;
    System.out.println(a == b); // prints true

    String str1 = “hello”;
    String str2 = “hello”;
    String str3 = new String(“hello”);
    System.out.println(str1 == str2); // prints true
    System.out.println(str1 == str3); // prints false

  6. equals() method:
  7. For primitive data types, the equals() method has not been overridden and still uses == for comparison.
  8. By default, for reference data types, the equals() method is the same as ==, comparing if the references are equal.
  9. 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.

  10. For example,
  11. The Person class defines a method to check if two Person objects are equal based on their name and age.
  12. Example of use:
  13. 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:

  1. It is used to compare the values of primitive data types and to check if the references of reference data types are equal.
  2. 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.
bannerAds