Here’s a clear explanation of the difference between ==
and .equals()
in Java:
==
Operator:- Purpose: Checks if two references point to the same object in memory.
- Use Case: Used for comparing primitive data types (e.g.,
int
,char
) or object references. - Example:
String s1 = new String("Hello"); String s2 = new String("Hello"); System.out.println(s1 == s2); // false (different memory locations)
.equals()
Method:- Purpose: Compares the contents (value) of two objects for equality.
- Use Case: Used for comparing the actual data inside objects (e.g., strings, custom objects).
- Can Be Overridden: Classes like
String
andInteger
override.equals()
to compare values. - Example:
String s1 = new String("Hello"); String s2 = new String("Hello"); System.out.println(s1.equals(s2)); // true (same content)
Key Difference:
==
: Checks if two references point to the same object..equals()
: Checks if two objects have the same content.
Note:
For primitive types like int
, ==
compares the values directly. For objects, use .equals()
to compare their values.