Java tutorials > Core Java Fundamentals > Basics and Syntax > What is the difference between `==` and `.equals()`?
What is the difference between `==` and `.equals()`?
The `==` Operator: Comparing References
public class EqualityExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
System.out.println("str1 == str2: " + (str1 == str2)); // Output: true
System.out.println("str1 == str3: " + (str1 == str3)); // Output: false
}
}
The `.equals()` Method: Comparing Content
public class EqualsExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = new String("Hello");
System.out.println("str1.equals(str2): " + str1.equals(str2)); // Output: true
Integer num1 = new Integer(5);
Integer num2 = new Integer(5);
System.out.println("num1.equals(num2): " + num1.equals(num2)); // Output: true
}
}
Concepts Behind the Snippet
Real-Life Use Case Section
Best Practices
Interview Tip
When to Use Them
Alternatives
Pros of `.equals()`
Cons of `.equals()`
FAQ
-
Why should I override `hashCode()` when I override `.equals()`?
The contract of `hashCode()` states that if two objects are equal according to `.equals()`, then they must have the same hash code value. This is crucial for the proper functioning of hash-based collections like `HashMap` and `HashSet`. If you override `.equals()` but not `hashCode()`, you risk violating this contract, which can lead to unpredictable behavior when using these collections. For example, you might not be able to retrieve objects from a `HashMap` even if they are logically equal. -
What happens if I don't override `.equals()`?
If you don't override `.equals()`, the default implementation from the `Object` class will be used, which simply compares object references using `==`. This means that two objects will only be considered equal if they are the exact same instance in memory. This might be acceptable for some classes, but for many classes, it's important to compare objects based on their content. -
Can I use `==` to compare strings?
While it *can* work in some cases, using `==` to compare strings is generally not recommended. String literals in the string pool are often interned, so `==` might return `true` for strings with the same content. However, strings created using the `new String()` constructor will not be interned, and `==` will return `false` even if the content is the same. Always use `.equals()` to compare the content of strings.