The Object class

Every Java class inherits from java.lang.Object, directly or through its superclasses, so every object has the same eleven methods. Their defaults are deliberately minimal: identity-based equality, a hash code with no meaning, and a toString of class name plus hex digits. This page explains each method and what lies behind it, shows what the defaults do and how to override them, looks at identity hash codes and getClass in detail, compares clone with copy methods, and ends with the java.util.Objects helpers.

Contents

The root of every class

A class that does not name a superclass extends java.lang.Object. Arrays are objects too, and every interface type can be assigned to Object. That makes Object the type of "anything", used by older collections, by equals(Object) and by reflection. Its methods fall into three groups:

The methods of java.lang.Object
MethodDefault behaviourOverride?
toString()Class name, @, identity hash code in hexAlmost always, for logs and debugging
equals(Object)Identity: this == otherFor value types; see equals and hashCode
hashCode()An identity hash code, unrelated to the fieldsAlways together with equals
getClass()The runtime class of the objectCannot be overridden (it is final)
clone()Protected; field-by-field copy if the class implements CloneableRarely; prefer copy constructors or factories
wait() (three forms), notify(), notifyAll()Thread coordination on the object's monitorCannot be overridden (all final)
finalize()Does nothing; deprecated since Java 9, for removal since Java 18Never; use Cleaner or AutoCloseable

Each object also carries a header with a mark word, used for the identity hash code, locking and garbage collection, and a pointer to its class. That is where the default hashCode and the monitor used by wait and synchronized live; see memory management for the header's size. Records (Java 16) generate toString, equals and hashCode from their components, which is why they appear in several examples here. The programs ran on JDK 21.

Default and overridden methods, and the Objects helpers

A class without overrides and a Product class that overrides toString, equals and hashCode by SKU are compared side by side. The second half uses the java.util.Objects utility class (Java 7, extended in Java 9), which supplies the null-safe versions of these operations.

Java
import java.util.Objects;

public class ObjectMethods {

    static class Plain {
        final int id;

        Plain(int id) {
            this.id = id;
        }
    }

    static class Product {
        final String sku;
        final double price;

        Product(String sku, double price) {
            this.sku = sku;
            this.price = price;
        }

        @Override
        public String toString() {
            return "Product[sku=" + sku + ", price=" + price + "]";
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof Product p && p.sku.equals(sku);
        }

        @Override
        public int hashCode() {
            return Objects.hash(sku);
        }
    }

    public static void main(String[] args) {
        Object o = new Plain(7);
        // Default toString: class name, '@', hash code in hex
        System.out.println("default toString matches Class@hex: "
                + o.toString().matches("ObjectMethods\\$Plain@[0-9a-f]+"));
        System.out.println("overridden toString: " + new Product("A-1", 9.5));

        System.out.println("default equals is identity: "
                + new Plain(1).equals(new Plain(1)));
        System.out.println("overridden equals by sku:   "
                + new Product("A-1", 9.5).equals(new Product("A-1", 12.0)));

        // getClass: the runtime class, even through a supertype reference
        Object p = new Product("B-2", 1);
        System.out.println("getClass: " + p.getClass().getSimpleName()
                + ", superclass: " + p.getClass().getSuperclass().getSimpleName());

        // Objects helpers
        String missing = null;
        System.out.println("Objects.toString(null, \"n/a\"): " + Objects.toString(missing, "n/a"));
        String chosen = Objects.requireNonNullElse(missing, "default");
        System.out.println("Objects.requireNonNullElse: " + chosen);
        try {
            Objects.requireNonNull(missing, "name must not be null");
        } catch (NullPointerException e) {
            System.out.println("requireNonNull: " + e.getMessage());
        }
        System.out.println("Objects.equals(null, null): " + Objects.equals(null, null)
                + ", Objects.hash(\"A-1\") == Objects.hash(\"A-1\"): "
                + (Objects.hash("A-1") == Objects.hash("A-1")));
        try {
            Objects.checkIndex(5, 3);                      // Java 9
        } catch (IndexOutOfBoundsException e) {
            System.out.println("checkIndex(5, 3): " + e.getMessage());
        }
    }
}

Output:

Output
default toString matches Class@hex: true
overridden toString: Product[sku=A-1, price=9.5]
default equals is identity: false
overridden equals by sku:   true
getClass: Product, superclass: Object
Objects.toString(null, "n/a"): n/a
Objects.requireNonNullElse: default
requireNonNull: name must not be null
Objects.equals(null, null): true, Objects.hash("A-1") == Objects.hash("A-1"): true
checkIndex(5, 3): Index 5 out of bounds for length 3
  • The default toString is ObjectMethods$Plain@ followed by hex digits that change from run to run, which is why the program checks the pattern instead of printing it. An overridden toString that shows the fields makes logs and debugger views useful.
  • Two Plain objects with the same id were not equal: the default equals compares identity. Two products with the same SKU but different prices were equal, because equals was overridden to compare the SKU only, and hashCode was overridden to match, as the contract requires.
  • getClass() returned the runtime class Product although the variable was declared as Object; its superclass is Object.
  • The Objects methods handle null: toString(null, "n/a") gives a default, requireNonNullElse (Java 9) picks a fallback, requireNonNull fails fast with a message, equals(null, null) is true without a NullPointerException, and hash(...) combines fields for hashCode. checkIndex (Java 9) throws the same message the JDK's own collections use.

Identity hash codes

The default hashCode() is often described as "the memory address", which is wrong in HotSpot. The program checks what an identity hash really guarantees: stability across garbage collection, its use in toString, its independence from overridden hashCode, and uniqueness.

Java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.List;

public class IdentityHash {

    record Point(int x, int y) { }       // records override equals and hashCode

    public static void main(String[] args) {
        Object o = new Object();
        int before = o.hashCode();

        // Move the object around: allocate garbage and collect, so the GC may relocate it
        List<byte[]> garbage = new ArrayList<>();
        for (int i = 0; i < 200; i++) {
            garbage.add(new byte[100000]);
        }
        garbage.clear();
        System.gc();
        System.out.println("identity hash unchanged after GC: " + (o.hashCode() == before));
        System.out.println("toString ends with the hash in hex: "
                + o.toString().endsWith("@" + Integer.toHexString(before)));

        // Overriding hashCode does not change the identity hash
        Point a = new Point(1, 2);
        Point b = new Point(1, 2);
        System.out.println("equal records, same hashCode(): " + (a.hashCode() == b.hashCode()));
        System.out.println("identityHashCode differs:       "
                + (System.identityHashCode(a) != System.identityHashCode(b)));

        // Identity hashes are not unique: count collisions among a million objects
        Set<Integer> seen = new HashSet<>();
        int collisions = 0;
        for (int i = 0; i < 1000000; i++) {
            if (!seen.add(System.identityHashCode(new Object()))) {
                collisions++;
            }
        }
        System.out.println("1,000,000 new Objects, identity hash collisions > 0: "
                + (collisions > 0));
    }
}

Output:

Output
identity hash unchanged after GC: true
toString ends with the hash in hex: true
equal records, same hashCode(): true
identityHashCode differs:       true
1,000,000 new Objects, identity hash collisions > 0: true
  • The hash code stayed the same after a collection that may have moved the object. HotSpot generates the identity hash the first time it is requested, from a thread-local pseudo-random generator by default, and stores it in the object's header, so moving the object does not change it.
  • The default toString uses exactly that value in hex.
  • Two equal records had the same hashCode(), as their generated method requires, but different System.identityHashCode values. identityHashCode always returns the default hash, whatever the class overrides; IdentityHashMap is built on it.
  • Among a million new objects, some identity hash codes collided. The hash is an int derived from random numbers, not an id: never use it, or a default toString, as a unique key.

toString traps

toString is called implicitly by string concatenation, println and loggers, so its gaps show up everywhere. The program prints arrays, a null, a list that contains itself and a pair of objects that point at each other.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ToStringTraps {

    static class Node {
        final String name;
        Node next;

        Node(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return name + " -> " + next;                // recursive through next
        }
    }

    public static void main(String[] args) {
        int[] numbers = {3, 1, 2};
        int[][] grid = {{1, 2}, {3, 4}};
        System.out.println("array toString looks like [I@hex: "
                + numbers.toString().matches("\\[I@[0-9a-f]+"));
        System.out.println("Arrays.toString:     " + Arrays.toString(numbers));
        System.out.println("Arrays.deepToString: " + Arrays.deepToString(grid));

        // Concatenation and println use String.valueOf, which handles null
        Object nothing = null;
        System.out.println("concatenated null: " + nothing);

        // The JDK collections guard against containing themselves
        List<Object> self = new ArrayList<>();
        self.add("item");
        self.add(self);
        System.out.println("list containing itself: " + self);

        // Your own toString does not: a cycle overflows the stack
        Node a = new Node("a");
        Node b = new Node("b");
        a.next = b;
        b.next = a;
        try {
            System.out.println(a);
        } catch (StackOverflowError e) {
            System.out.println("cyclic toString: StackOverflowError");
        }
    }
}

Output:

Output
array toString looks like [I@hex: true
Arrays.toString:     [3, 1, 2]
Arrays.deepToString: [[1, 2], [3, 4]]
concatenated null: null
list containing itself: [item, (this Collection)]
cyclic toString: StackOverflowError
  • Arrays do not override toString, so an int[] prints as [I@ plus a hash. Arrays.toString prints the elements, and Arrays.deepToString handles nested arrays.
  • Concatenating null printed "null" without an exception, because concatenation and println go through String.valueOf. Calling nothing.toString() directly would have thrown NullPointerException.
  • A list that contains itself printed the element as "(this Collection)": AbstractCollection.toString checks for that case. A hand-written toString that follows references has no such protection, and the two nodes pointing at each other recursed until StackOverflowError. For objects in a graph, print ids of related objects, not the objects themselves; JPA entities and bidirectional relations are the usual victims.

getClass() and its surprises

getClass() returns the exact runtime class, which is not always the class you expect. The program prints it for a collection behind an interface, two arrays, an anonymous class, a lambda, and two enum constants, one of which has its own body.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

public class GetClassDemo {

    enum Op {
        PLUS,
        MINUS {                              // a constant with a body is its own subclass
            @Override
            int apply(int a, int b) {
                return a - b;
            }
        };

        int apply(int a, int b) {
            return a + b;
        }
    }

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        Object anon = new Object() { };
        Supplier<String> lambda = () -> "x";

        System.out.println("List variable, getClass(): " + list.getClass().getName());
        System.out.println("int[]:                     " + new int[0].getClass().getName());
        System.out.println("String[][]:                " + new String[0][0].getClass().getName());
        System.out.println("anonymous class:           " + anon.getClass().getName());
        System.out.println("lambda is hidden class:    " + lambda.getClass().isHidden());

        // The enum trap: getClass() of a constant with a body is not the enum type
        System.out.println("PLUS.getClass():           " + Op.PLUS.getClass().getName());
        System.out.println("MINUS.getClass():          " + Op.MINUS.getClass().getName());
        System.out.println("MINUS.getDeclaringClass(): " + Op.MINUS.getDeclaringClass().getName());
        System.out.println("MINUS.getClass() == Op.class: " + (Op.MINUS.getClass() == Op.class));

        // getClass() vs instanceof
        Object s = "text";
        System.out.println("\"text\" instanceof CharSequence: " + (s instanceof CharSequence)
                + ", getClass() == CharSequence.class: " + (s.getClass() == CharSequence.class));
    }
}

Output:

Output
List variable, getClass(): java.util.ArrayList
int[]:                     [I
String[][]:                [[Ljava.lang.String;
anonymous class:           GetClassDemo$1
lambda is hidden class:    true
PLUS.getClass():           GetClassDemo$Op
MINUS.getClass():          GetClassDemo$Op$1
MINUS.getDeclaringClass(): GetClassDemo$Op
MINUS.getClass() == Op.class: false
"text" instanceof CharSequence: true, getClass() == CharSequence.class: false
  • A variable of type List holds an ArrayList, and getClass() reports the concrete class. Array classes have JVM names: [I for int[], [[Ljava.lang.String; for String[][]. getSimpleName() gives the readable form int[].
  • An anonymous class is named after its enclosing class with a number, GetClassDemo$1, and a lambda's class is a hidden class generated at run time, as described on the functional interfaces page.
  • The trap: an enum constant with its own body, MINUS, is an instance of an anonymous subclass, GetClassDemo$Op$1. Code that checks constant.getClass() == Op.class or puts constants into maps keyed by getClass() breaks for such constants. getDeclaringClass() always returns the enum type.
  • getClass() tests the exact class, while instanceof accepts subtypes and interfaces: a String is an instance of CharSequence, but its class is not CharSequence.class. That difference is the heart of the debate about which one to use in equals, covered on the equals and hashCode page.

clone() and copying objects

Object.clone() makes a field-by-field copy, but only for classes that implement the marker interface Cloneable, and it is protected, so a class must override it to make it usable. A playlist with a list of songs shows what "field by field" means for a field that refers to a mutable object.

Java
import java.util.ArrayList;
import java.util.List;

public class CloneDemo {

    static class Playlist implements Cloneable {
        String name;
        List<String> songs = new ArrayList<>();

        Playlist(String name) {
            this.name = name;
        }

        @Override
        public Playlist clone() {
            try {
                return (Playlist) super.clone();          // shallow: fields are copied as-is
            } catch (CloneNotSupportedException e) {
                throw new AssertionError(e);
            }
        }

        Playlist deepCopy() {                             // a copy method is usually clearer
            Playlist copy = new Playlist(name);
            copy.songs = new ArrayList<>(songs);
            return copy;
        }
    }

    static class NotCloneable {
        Object tryClone() throws CloneNotSupportedException {
            return super.clone();
        }
    }

    public static void main(String[] args) throws Exception {
        Playlist original = new Playlist("road trip");
        original.songs.add("song A");

        Playlist shallow = original.clone();
        Playlist deep = original.deepCopy();
        original.songs.add("song B");

        System.out.println("shallow clone shares the list: " + shallow.songs);
        System.out.println("deep copy has its own list:    " + deep.songs);

        try {
            new NotCloneable().tryClone();
        } catch (CloneNotSupportedException e) {
            System.out.println("without Cloneable: " + e.getClass().getSimpleName());
        }

        int[] arr = {1, 2, 3};
        int[] copy = arr.clone();                          // arrays clone easily
        copy[0] = 99;
        System.out.println("array clone is independent: " + arr[0]);
    }
}

Output:

Output
shallow clone shares the list: [song A, song B]
deep copy has its own list:    [song A]
without Cloneable: CloneNotSupportedException
array clone is independent: 1
  • The clone shared the original's list, so a song added to the original later appeared in the clone too: clone() copies references, not the objects they point to. This is a shallow copy. The deepCopy method made a new list and stayed independent.
  • Calling super.clone() in a class without Cloneable threw CloneNotSupportedException. The Cloneable interface has no methods; it only switches on the behaviour of Object.clone(), an unusual design that Effective Java calls broken.
  • Arrays implement clone() publicly, and for an array of primitives the copy is fully independent. For an array of objects it is again shallow.
  • Prefer a copy constructor (new Playlist(other)) or a static factory: they work with final fields, need no casts or checked exceptions, and make the deep or shallow choice explicit. Immutable objects, such as records with immutable components, need no copying at all; see immutability.

wait and notify

Every object has a monitor, and the wait and notify methods let threads wait for a condition on it. A one-message mailbox shows the basic pattern, and the last call shows the rule that the calling thread must hold the monitor.

Java
public class WaitNotify {

    private String message;                  // guarded by 'this'

    synchronized void put(String m) {
        message = m;
        notifyAll();                         // wake threads waiting on this object
    }

    synchronized String take() throws InterruptedException {
        while (message == null) {            // always wait in a loop
            wait();                          // releases the lock while waiting
        }
        String m = message;
        message = null;
        return m;
    }

    public static void main(String[] args) throws InterruptedException {
        WaitNotify box = new WaitNotify();
        Thread consumer = new Thread(() -> {
            try {
                System.out.println("consumer got: " + box.take());
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        consumer.start();
        Thread.sleep(100);
        box.put("hello");
        consumer.join();

        try {
            box.wait();                      // not holding the lock
        } catch (IllegalMonitorStateException e) {
            System.out.println("wait() without the lock: IllegalMonitorStateException");
        }
    }
}

Output:

Output
consumer got: hello
wait() without the lock: IllegalMonitorStateException
  • The consumer waited inside take() until the producer stored a message and called notifyAll(). wait() releases the monitor while waiting and takes it back before returning, which is why it must be called inside synchronized.
  • Calling wait() without holding the monitor threw IllegalMonitorStateException.
  • The condition is checked in a while loop, because a waiting thread can wake up without the condition being true. For the full rules and the traps, see synchronized and volatile; in new code, the classes in java.util.concurrent are usually simpler.

Overriding checklist

What to do with each Object method
MethodRecommendation
toStringOverride with the fields that identify the object; never parse its output
equals and hashCodeOverride both or neither; use a record when the class is a plain value
Unique idsUse a real id field, never hashCode or the default toString
Class checksinstanceof for "is a kind of", getClass() for "exactly this class"; getDeclaringClass() for enums
CopyingCopy constructors or factories; implement clone only for compatibility
Waiting for conditionsjava.util.concurrent tools; wait in a loop with notifyAll in low-level code
CleanupAutoCloseable and try-with-resources, never finalize
Null-safe comparisons and checksObjects.equals, Objects.hash, Objects.requireNonNull