Difference Between == and equals() in Java

Difference Between == and equals() in java
When learning Java, one of the most common sources of confusion is the difference between the == operator and the equals() method. Although both are used for comparison, they behave very differently depending on the context. Understanding this distinction is essential for writing correct and bug-free code.
What is == in Java?
The == operator is used to compare two values or references.
For primitive data types (such as
int,double,char),==compares the actual values.For objects,
==compares whether the two references point to the same memory location.
Example:
int a = 10;
int b = 10;
System.out.println(a == b); // true
String s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1 == s2); // falseIn the example above, even though s1 and s2 have the same content, they are stored in different memory locations, so == returns false.
What is equals() in Java?
The equals() method is defined in the Object class and is used to compare the logical equality (content) of two objects.
By default,
equals()behaves like==(reference comparison).However, many classes such as
String,Integer, and collections override this method to compare actual content.
Example:
String s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1.equals(s2)); // trueHere, equals() returns true because it compares the values inside the objects, not their memory addresses.
Key Differences
Feature==equals()TypeOperatorMethodUsed forPrimitives & object referencesObjects onlyComparisonMemory address (for objects)Content (logical equality)Can be overriddenNoYes
Simple Explanation
Use
==when you want to check if two variables refer to the same object.Use
equals()when you want to check if two objects have the same value.
Common Mistake
Many beginners mistakenly use == to compare strings:
String a = "Hello";
String b = "Hello";
System.out.println(a == b); // may be true (due to String pool)This can sometimes return true because of Java’s String Pool, but it is not reliable. Always use:
a.equals(b);Conclusion
Understanding the difference between == and equals() is crucial in Java programming. While == is suitable for comparing primitive values or checking reference equality, equals() should be used when comparing the actual content of objects. Choosing the wrong one can lead to subtle and hard-to-detect bugs.
