In Java, the == operator is used to compare the memory addresses of two objects, while the equals() method is used to compare the content or values of two objects.
When using the == operator to compare two objects, Java checks if the memory addresses of the two objects are the same. If the memory addresses are the same, then the two objects are considered equal. If the memory addresses are different, then the two objects are considered not equal, even if their contents or values are the same.
When using the equals() method to compare two objects, Java checks if the contents or values of the two objects are the same. The equals() method is a method that is defined in the Object class, which is the superclass of all classes in Java. Classes can override the equals() method to define their own custom equality check based on the contents or values of the objects.
Here’s an example Java program that demonstrates the difference between == and equals():
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Person)) {
return false;
}
Person other = (Person) obj;
return this.name.equals(other.name)
&& this.age == other.age;
}
}
public class Main {
public static void main(String[] args) {
Person person1 = new Person("Alice", 25);
Person person2 = new Person("Alice", 25);
Person person3 = person1;
System.out.println(person1 == person2); // false
System.out.println(person1 == person3); // true
System.out.println(person1.equals(person2)); // true
System.out.println(person1.equals(person3)); // true
}
}
In this program, we define a Person class that represents a person with a name and an age. We also define an equals() method that checks if two Person objects have the same name and age.
In the Main class, we create three Person objects (person1, person2, and person3). person1 and person2 have the same name and age, while person3 is a reference to person1.
We then use the == operator to compare the memory addresses of person1 and person2, and person1 and person3. We also use the equals() method to compare the contents or values of person1 and person2, and person1 and person3.
When we run this program, it outputs the following:
false
true
true
true
This demonstrates how the == operator compares the memory addresses of objects, while the equals() method compares the contents or values of objects. Note that person1 and person2 have the same contents or values, but different memory addresses, so the == operator returns false, while the equals() method returns true. On the other hand, person1 and person3 have the same memory address, so the == operator returns true, while the equals() method also returns true.