-1

I am new to Java and StackOverflow but as i have read some of the answers about equals they stated :

Equals method compares two objects for their identity and if they are

identical it returns TRUE . whereas if you don't override the method Equals

it acts like ==(which returns true if 2 variables refer to the same object).

Integer x = new Integer(4);  

Integer y = new Integer(4); 

System.out.println(x.equals(y));  

System.out.println(x == y);

If the queries above are correct why does this code print TRUE and FALSE since we are not overriding the method equals?

Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53
R AND B
  • 51
  • 2
  • 9
  • 1
    If a class does not override the equals method, then it defaults to the equals(Object o) method of the closest parent class that has overridden this method. can you explain me this query as simple as possible ? – R AND B May 01 '19 at 16:31
  • @Naya i am not asking for == and equals difference. – R AND B May 01 '19 at 16:38

1 Answers1

3

Because class Integer does override the equals method and it's implementation is the following:

public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
}
Tarmo
  • 3,851
  • 2
  • 24
  • 41
  • so does String class? – R AND B May 01 '19 at 16:37
  • Yes. You can look the source of all the Java standard library classes yourself to see the implementation details. – Tarmo May 01 '19 at 16:38
  • ... or you can just read the classes' API docs: [Integer.equals(Object)](https://docs.oracle.com/javase/10/docs/api/java/lang/Integer.html#equals(java.lang.Object)); [String.equals(Object)](https://docs.oracle.com/javase/10/docs/api/java/lang/String.html#equals(java.lang.Object)). That's a better source for those details of standard library classes' behavior that users are meant to be able to rely upon. – John Bollinger May 01 '19 at 16:47