Difference Between == and .equals() in Java.

As a language, Java provides different mechanisms to compare objects and values. Two commonly used methods for comparison are the equals() method and the == operator. While they might seem similar, they serve different purposes and behave differently when used. Let's discuss each of them individually and understand which one should use in which condition.

Comparison Operator in Java

== Operator.

In Java, the == operator is used to compare primitive data types and object references. When comparing primitive data types, it checks whether the values are the same. When comparing object references, it checks whether the references point to the same memory location.

Example Java Code:
public class EqualityExample {
    public static void main(String[] args) {
        // Primitive types
        int x = 5;
        int y = 5;
        System.out.println(x == y); // true

        // Object references
        String str1 = new String("Hello");
        String str2 = new String("Hello");
        System.out.println(str1 == str2); // false
    }
}
Output:
true
false

Explanation:

In the example, x == y is true because the values of x and y are both 5. However, str1 == str2 is false because the == operator compares the references, and str1 and str2 point to different memory locations.

equals() Methods.

The equals() method is a method provided by the Object class and is meant to be overridden by classes that need to define a logical equality. By default, the equals() method in the Object class compares object references, similar to the == operator.

Example Java Code:
public class EqualityExample {
    public static void main(String[] args) {
        String str1 = new String("Hello");
        String str2 = new String("Hello");
        System.out.println(str1.equals(str2)); // true
    }
}
Output:
true

Explanation:

In this example, str1.equals(str2) is true because the String class overrides the equals() method to compare the actual content of the strings, not just the references.

It's important to note that many classes in Java, like String, Integer, and others, override the equals() method to provide meaningful content-based comparison. When working with custom classes, you should override equals() to suit the specific equality criteria for instances of your class.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS