-3

does anyone have an explanation for the a.equals(b) and a==b in the above code..? you can refer the image also, which shows the output for the following code.

public class Main
{
    public static void main(String[] args) {
            Integer  a=new Integer(10);
            double  b=10;
            System.out.println(a==b);
            System.out.println(a.equals(b));
    }
}

enter image description here

Sujeet Sinha
  • 2,417
  • 2
  • 18
  • 27
dhanush_r
  • 1
  • 1
  • 2
    Does this answer your question? [What is the difference between == and equals() in Java?](https://stackoverflow.com/questions/7520432/what-is-the-difference-between-and-equals-in-java) – akuzminykh May 09 '20 at 05:58
  • Does this answer your question? [Why would you use String.Equals over ==?](https://stackoverflow.com/questions/1659097/why-would-you-use-string-equals-over) – Sujeet Sinha May 09 '20 at 05:58
  • Also useful: https://stackoverflow.com/questions/13297207/is-it-valid-to-compare-a-double-with-an-int-in-java – Abhyudaya Sharma May 09 '20 at 06:03

2 Answers2

1

If you see the equals method in Integer class. Since the b is not the instance of Integer it returns false.

public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}
backdoor
  • 891
  • 1
  • 6
  • 18
0

From the documentation .equals() Compares this object to the specified object. The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object.

Since b is NOT an Integer object, it returns false.

Pranav Nachnekar
  • 115
  • 1
  • 10