Questions
What is the difference between `==` and `.equals()` in Java?
The Scenario
You are a backend engineer at a fintech company. You are writing a new service that needs to compare two objects to see if they are equal. You are not sure whether to use the == operator or the .equals() method.
The Challenge
Explain the difference between the == operator and the .equals() method in Java. When would you use one over the other?
A junior engineer might think that they are interchangeable. They might not be aware of the difference between reference equality and value equality.
A senior engineer would be able to provide a detailed explanation of the differences between `==` and `.equals()`. They would also be able to explain the trade-offs between each approach and would have a clear recommendation for which one to use in this use case.
Step 1: Understand the Key Differences
| Feature | == | .equals() |
|---|---|---|
| Purpose | To check for reference equality. | To check for value equality. |
| Behavior | Returns true if the two references point to the same object in memory. | Returns true if the two objects have the same value. |
| Use Cases | When you need to check if two references point to the same object. | When you need to check if two objects have the same value. |
Step 2: Choose the Right Tool for the Job
For our use case, we should use the .equals() method. This is because we want to check if the two objects have the same value, not if they are the same object in memory.
Step 3: Code Examples
Here are some code examples that show the difference between the two approaches:
==:
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2); // falseIn this example, s1 == s2 returns false because s1 and s2 are two different objects in memory, even though they have the same value.
.equals():
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1.equals(s2)); // trueIn this example, s1.equals(s2) returns true because the String class overrides the .equals() method to check for value equality.
Overriding .equals()
When you create your own custom classes, you should always override the .equals() method to provide a meaningful implementation of value equality. When you override .equals(), you should also override the .hashCode() method.
Practice Question
You have two `Integer` objects with the same value. What will `==` return?