Difference Between == Operator and equals() Method in java

equals() is method and == is operator

== operators used for reference comparison and address comparison

equals() method used for content comparison.

 In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates the comparison of values in the objects.


Approach

Java


public class JavaEqualsTest {
    public static void main(String[] args) {
        String s1 = new String("BEINGCODEEXPERT");
        String s2 = new String("BEINGCODEEXPERT");
        String s3 = "BEINGCODEEXPERT";
        // Reference comparison
        System.out.println(s1 == s2);
        System.out.println(s1 == s3);
        // Content comparison
        System.out.println(s1.equals(s2));
        System.out.println(s1.equals(s3));

        int num1 = 10;
        int num2 = 10;
        System.out.println(num1 == num2);
    }
}

Output

false
false
true
true
true


No comments:

Post a Comment