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.ObjectObjectObjectequals(Object)
| Method | Default behaviour | Override? |
|---|---|---|
toString() | Class name, @ | Almost always, for logs and debugging |
equals(Object) | Identity: this == other | For value types; see |
hashCode() | An identity hash code, unrelated to the fields | Always together with equals |
getClass() | The runtime class of the object | Cannot be overridden (it is final |
clone() | Protected; field-by-field copy if the class implements Cloneable | Rarely; prefer copy constructors or factories |
wait()notify()notifyAll() | Thread coordination on the object's monitor | Cannot be overridden (all final |
finalize() | Does nothing; deprecated since Java 9, for removal since Java 18 | Never; use 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 hashCodewaitsynchronizedtoStringequalshashCode
Default and overridden methods, and the Objects helpers
A class without overrides and a ProducttoStringequalshashCodejava.util.Objects
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:
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
istoString followed by hex digits that change from run to run, which is why the program checks the pattern instead of printing it. An overriddenObjectMethods$Plain@ that shows the fields makes logs and debugger views useful.toString - Two
objects with the same id were not equal: the defaultPlain compares identity. Two products with the same SKU but different prices were equal, becauseequals was overridden to compare the SKU only, andequals was overridden to match, as the contract requires.hashCode returned the runtime classgetClass() although the variable was declared asProduct ; its superclass isObject .Object- The
methods handleObjects :null gives a default,toString(null, "n/a") (Java 9) picks a fallback,requireNonNullElse fails fast with a message,requireNonNull is true without aequals(null, null) , andNullPointerException combines fields forhash(...) .hashCode (Java 9) throws the same message the JDK's own collections use.checkIndex
Identity hash codes
The default hashCode()toStringhashCode
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:
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
uses exactly that value in hex.toString - Two equal records had the same
, as their generated method requires, but differenthashCode() values.System.identityHashCode always returns the default hash, whatever the class overrides;identityHashCode is built on it.IdentityHashMap - Among a million new objects, some identity hash codes collided. The hash is an
derived from random numbers, not an id: never use it, or a defaultint , as a unique key.toString
toString traps
toStringprintlnnull
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:
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
, so antoString prints asint[] plus a hash.[I@ prints the elements, andArrays.toString handles nested arrays.Arrays.deepToString - Concatenating
printed "null" without an exception, because concatenation andnull go throughprintln . CallingString.valueOf directly would have thrownnothing.toString() .NullPointerException - A list that contains itself printed the element as "(this Collection)":
checks for that case. A hand-writtenAbstractCollection.toString that follows references has no such protection, and the two nodes pointing at each other recursed untiltoString . For objects in a graph, print ids of related objects, not the objects themselves; JPA entities and bidirectional relations are the usual victims.StackOverflowError
getClass() and its surprises
getClass()
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:
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
holds anList , andArrayList reports the concrete class. Array classes have JVM names:getClass() for[I ,int[] for[[Ljava.lang.String; .String[][] gives the readable formgetSimpleName() .int[] - An anonymous class is named after its enclosing class with a number,
, and a lambda's class is a hidden class generated at run time, as described on theGetClassDemo$1functional interfaces page . - The trap: an enum constant with its own body,
, is an instance of an anonymous subclass,MINUS . Code that checksGetClassDemo$Op$1 or puts constants into maps keyed byconstant.getClass() == Op.class breaks for such constants.getClass() always returns the enum type.getDeclaringClass() tests the exact class, whilegetClass() accepts subtypes and interfaces: ainstanceof is an instance ofString , but its class is notCharSequence . That difference is the heart of the debate about which one to use inCharSequence.class , covered on theequalsequals and hashCode page .
clone() and copying objects
Object.clone()Cloneableprotected
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:
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:
copies references, not the objects they point to. This is a shallow copy. Theclone() method made a new list and stayed independent.deepCopy - Calling
in a class withoutsuper.clone() threwCloneable . TheCloneNotSupportedException interface has no methods; it only switches on the behaviour ofCloneable , an unusual design that Effective Java calls broken.Object.clone() - Arrays implement
publicly, and for an array of primitives the copy is fully independent. For an array of objects it is again shallow.clone() - Prefer a copy constructor (
) or a static factory: they work withnew Playlist(other) 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; seefinalimmutability .
wait and notify
Every object has a monitor, and the waitnotify
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:
consumer got: hello
wait() without the lock: IllegalMonitorStateException
- The consumer waited inside
until the producer stored a message and calledtake() .notifyAll() releases the monitor while waiting and takes it back before returning, which is why it must be called insidewait() .synchronized - Calling
without holding the monitor threwwait() .IllegalMonitorStateException - The condition is checked in a
loop, because a waiting thread can wake up without the condition being true. For the full rules and the traps, seewhilesynchronized and volatile ; in new code, the classes in are usually simpler.java.util.concurrent
Overriding checklist
| Method | Recommendation |
|---|---|
toString | Override with the fields that identify the object; never parse its output |
equalshashCode | Override both or neither; use a record when the class is a plain value |
| Unique ids | Use a real id field, never hashCodetoString |
| Class checks | instanceofgetClass()getDeclaringClass() |
| Copying | Copy constructors or factories; implement clone |
| Waiting for conditions | java.util.concurrentwaitnotifyAll |
| Cleanup | AutoCloseablefinalize |
| Null-safe comparisons and checks | Objects.equalsObjects.hashObjects.requireNonNull |