What is the difference between '==' and the equals() method in Java?
In Java, `==` and `equals()` test different things and the distinction is fundamental to writing correct code.
`==` is the identity operator. For primitive types (`int`, `double`, `boolean`, etc.), it compares values directly — `5 == 5` is `true`. For object references, it compares memory addresses: it is `true` only if both variables point to the exact same object in memory.
`equals()` is a method defined on `Object` that tests logical equality. The default implementation in `Object` uses `==` (same reference), but most classes override it to compare content. `String.equals()` compares character sequences. `Integer.equals()` compares numeric values. If you don't override `equals()`, you get reference comparison by default.
The classic example: `String a = new String("hello"); String b = new String("hello");` — `a == b` is `false` (different objects on the heap), but `a.equals(b)` is `true` (same content).
Key practical rules: - Always use `equals()` to compare object content. - Use `==` only to check if two references point to the exact same instance, or to compare primitives. - Never use `==` to compare boxed wrapper types like `Integer` or `Long` unless you know the values fall in the cached range (-128 to 127 for Integer) — and even then, don't rely on caching behavior. - Use `Objects.equals(a, b)` when either operand might be null, to avoid NullPointerException.
For `null`: `null == null` is `true`. Calling `.equals()` on a null reference throws `NullPointerException`. Calling `someObject.equals(null)` should return `false` by contract and does so in all standard library implementations.
| Aspect | == | equals() |
|---|---|---|
| Type | Operator | Method on Object |
| For primitives | Value comparison | N/A — primitives have no methods |
| For objects | Reference (identity) comparison | Logical value comparison |
| Default behavior | Reference equality (always) | Reference equality (unless overridden) |
| Null safety | null == null is true | Calling on null throws NPE |
| Override? | Cannot be overridden | Should be overridden with hashCode() |
Correctly explains reference vs value comparison and gives a concrete String example showing the difference.
Also covers null behavior, the Integer cache trap with ==, Objects.equals() for null safety, and the requirement to override hashCode() when overriding equals().
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment