== Operator:
- Compares the memory locations of two objects.
- Works for both primitive data types and objects.
- For primitive data types, it compares the actual values.
- For objects, it checks whether both objects refer to the same memory location, regardless of their values.
equals() method
- Compares the content of two objects.
- Works only for objects.
- Can be overridden in subclasses to define custom comparison behavior.
- By default, it compares the object's fields.
Here's a table summarizing the key differences:
Here are some additional points to consider:
For primitive data types, == and equals() are the same.
For objects, it is usually recommended to use the equals() method instead of the == operator, unless you specifically need to compare memory locations.
The equals() method of the String class overrides the default behavior and compares the string values instead of memory locations.
Here are some examples to illustrate the difference:
int b = 5;
System.out.println(a == b); // Output: true
System.out.println(a.equals(b)); // Output: true
String str2 = new String("Hello");
System.out.println(str1 == str2); // Output: false (different memory locations)
System.out.println(str1.equals(str2)); // Output: true (same content)
Here are some examples to illustrate the difference:
Example 1: Comparing primitive data types
int a = 5;int b = 5;
System.out.println(a == b); // Output: true
System.out.println(a.equals(b)); // Output: true
Example 2: Comparing object references
String str1 = "Hello";String str2 = new String("Hello");
System.out.println(str1 == str2); // Output: false (different memory locations)
System.out.println(str1.equals(str2)); // Output: true (same content)
Example 3: Overriding the equals() method
class Person {
String name;
int age;
@Override
public boolean equals(Object obj) {
if (obj instanceof Person) {
Person other = (Person) obj;
return name.equals(other.name) && age == other.age;
} else {
return false;
}
}
}
Person p1 = new Person();
p1.name = "John";
p1.age = 30;
Person p2 = new Person();
p2.name = "John";
p2.age = 30;
System.out.println(p1 == p2); // Output: false (different memory locations)
System.out.println(p1.equals(p2)); // Output: true (same content)
No comments:
Post a Comment