Difference between == and equals() method in Java

1. Introduction

In Java, comparing objects and primitives is a fundamental operation. The == operator and the equals() method are two ways to compare objects, but they serve different purposes. The == operator compares references or primitive values, while the equals() method is intended for checking logical equality.

2. Key Points

1. == checks if two references point to the same object or if two primitives have the same value.

2. equals() is a method in the Object class that checks if two objects are logically equal.

3. equals() can be overridden in a class to define custom equality logic.

4. Using == with objects often leads to unexpected results if you're looking for logical equality rather than reference identity.

3. Differences

== equals()
Compares primitives by value and objects by reference. Compares objects by the content in them.
Cannot be overridden. Can be overridden in any class to define a custom equality check.
Checks if two reference variables point to the same object. Checks if two objects are meaningfully equivalent.

4. Example

// Step 1: Create two string variables using the string literal
String example1 = "Hello";
String example2 = "Hello";

// Step 2: Create two string objects using the 'new' keyword
String object1 = new String("Hello");
String object2 = new String("Hello");

// Step 3: Use the == operator to compare the string variables and objects
System.out.println("Using == for literals: " + (example1 == example2)); // Compares string literals
System.out.println("Using == for objects: " + (object1 == object2)); // Compares object references

// Step 4: Use the equals() method to compare the string objects
System.out.println("Using equals for objects: " + object1.equals(object2)); // Compares string values

Output:

Using == for literals: true
Using == for objects: false
Using equals for objects: true

Explanation:

1. The string literals example1 and example2 refer to the same object in the string pool, so == returns true.

2. object1 and object2 are created with new, so they reference different objects, and == returns false.

3. The equals() method checks the content of object1 and object2, finds them identical, and returns true.

5. When to use?

- Use == to compare primitive values or when you need to check if two references point to the exact same object.

- Use equals() when you need to check if two objects are logically "equal", meaning they have the same content or state.

Comments