Search⌘ K

The Object Class

Understand how the Object class's equals method works, why it compares memory addresses by default, and why overriding both equals and hashCode is crucial for proper object equality and hash-based collections in Java. Explore examples to see how to implement these methods correctly.

We'll cover the following...
1.

What is the Object class?

Show Answer
Did you find this helpful?
Java
class HelloWorld {
public static void main( String args[] ) {
System.out.println((new ObjectSubclass()) instanceof Object);
}
}
class ObjectSubclass {
}
1.

What are the methods defined in the Object class?

Show Answer
Did you find this helpful?
Technical Quiz
1.

What is the output of the below snippet?

    String obj1 = new String("abc");
    String obj2 = new String("abc");
    System.out.println(obj1 == obj2);
A.

false

B.

true


1 / 4

The equals() method provided in the Object class uses the identity operator == to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. The equals() method provided by Object tests whether the object references are equal — that is, if the object references are pointing to the same address in memory. This is the reason the statement new Integer(5) == new Integer(5) will output false because the two integer objects have different memory ...