Bonus
== Operator in Java
The == operator in Java is used to compare two values — but what it compares depends on the type of data.
1. Primitive Data Types
For primitive types (int, float, char, boolean, etc.), == compares the actual values.
Example:
class PrimitiveComparison {
public static void main(String[] args) {
int a = 5;
int b = 5;
System.out.println("a == b: " + (a == b));
}
}
Output:
a == b: true
Explanation:
- Since both a and b hold the same value (5), == returns true.
2. Reference Types (Objects)
For objects, == compares the memory addresses (references) — i.e., whether both variables point to the same object in memory, not whether their contents are equal.
Example:
class ObjectComparison {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println("s1 == s2: " + (s1 == s2)); // false
System.out.println("s1.equals(s2): " + s1.equals(s2)); // true
}
}
Output:
s1 == s2: false
s1.equals(s2): true
Explanation:
- == checks if s1 and s2 point to the same object (they don’t).
- .equals() checks if contents are the same (they are).
3. String Literal Pool (Special Case)
When using string literals, Java optimizes and reuses them using a String pool, so == might return true.
Example:
class StringPoolCheck {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello";
System.out.println("s1 == s2: " + (s1 == s2));
}
}
Output:
s1 == s2: true
Explanation:
- Both s1 and s2 refer to the same object in the string pool, so == returns true.
4. Comparing with null
Example:
class NullCheck {
public static void main(String[] args) {
String str = null;
System.out.println("str == null: " + (str == null));
}
}
Output:
str == null: true
Explanation:
- You can safely use == to check if a reference is null.
Bonus Tip:
Use == only for primitives or reference checks.
For object content comparison, always use .equals():
Example:
import java.util.Objects;
class NullSafeEquals {
public static void main(String[] args) {
String a = null;
String b = null;
System.out.println(Objects.equals(a, b)); // true
}
}
Output:
true
Explanation:
- Objects.equals(a, b) is a null-safe method to compare two objects:
- If both are null, it returns true.
- If only one is null, it returns false.
- Otherwise, it checks a.equals(b).
This is much safer than:
a.equals(b); // NullPointerException if a is null
Summary:
| Type | == Compares | Use .equals()? | Example Result |
|---|---|---|---|
| Primitive | Actual value | No | 5 == 5 → true |
| Object | Memory reference (address) | Yes | new String("a") == new String("a") → false |
| String Literal | Pooled reference (optimized) | Careful | "abc" == "abc" → true |
| null | Checks if reference is null | No | str == null → true |