The == operator and equals() method are both used for comparison in Java, but they serve different purposes. The == operator compares primitive values or object references, whereas equals() compares the actual content or state of objects.
Key Points: • For primitive data types, == compares actual values. • For objects, == checks whether both references point to the same memory location. • equals() is used to compare the contents of two objects. • The default equals() implementation in Object behaves like ==, but many classes such as String override it to compare values. • In real-world applications, equals() is generally used when comparing object data.
Example: Two String objects may contain the same text but reside at different memory locations. In this case, == may return false, while equals() returns true.
Code Example:
public class Demo {
public static void main(String[] args) {
String str1 = new String("Java");
String str2 = new String("Java");System.out.println(str1 == str2); // false System.out.println(str1.equals(str2)); // true
}
}Quick Comparison:
== Operator • Compares primitive values • Compares object references • Checks memory location
equals() Method • Compares object content • Can be overridden by classes • Commonly used for business data comparison
Interview Tip: A concise interview answer is:
"== compares primitive values or object references, while equals() compares the actual content of objects. For object comparison, equals() is generally preferred because it checks logical equality rather than memory addresses."