toString
toString returns a text picture of an object. System.out.println, string concatenation, and most loggers call it. The default is the class name and a hash.
Detailed Explanation
When you print an object and see Payment@6d06d69c, you are looking at Object.toString: type name, @, identity hash in hex. That is enough to tell two instances apart and not enough to debug a payment. Override toString so the important fields appear.
The contract is loose. It should be short, readable, and safe to call at any time. It should not throw. It should not hit the network or the database. It should not include secrets (passwords, tokens, full card numbers). Logs last longer than you think, and toString is how objects enter logs when someone writes log.info("user {}", user).
Records generate a toString from their components. That is why Money[currency=INR, minor=100] appears without extra code. You can override it. Lombok and IDEs generate versions for ordinary classes. Prefer including fields that explain equality and identity, not every lazy collection.
toString is not a serialization format. Parsers should not depend on it. It is not a UI string; those need locale and should live on a formatter. It is not equals. Two objects can print the same and not be equal if you omitted a field.
You reach for an override on almost every domain type you will log or see in a debugger. You skip it on types that hold huge graphs (a JPA entity with lazy associations): printing them can load the database and recurse. For those, print the id and a flag, not the graph.
The cost of a heavy toString is hidden work in logging and in debugger tooltips. The cost of none is unreadable traces. Watch cycles: if Order prints Customer and Customer prints orders, you overflow the stack. Print an id for the back-reference. Arrays.toString and Arrays.deepToString exist because arrays keep Object.toString.
Code Examples
public class Payment {
private final String ref;
private final long minor;
public Payment(String ref, long minor) {
this.ref = ref;
this.minor = minor;
}
@Override
public String toString() {
return "Payment[" + ref + ", " + minor + "]";
}
public static void main(String[] args) {
System.out.println(new Payment("INV-9", 250)); // prints: Payment[INV-9, 250]
System.out.println("paid " + new Payment("INV-9", 250));
// prints: paid Payment[INV-9, 250]
}
}import java.util.Arrays;
public class ArrayPrint {
public static void main(String[] args) {
int[] xs = {1, 2, 3};
System.out.println(xs); // prints: [I@<hash> (default)
System.out.println(Arrays.toString(xs)); // prints: [1, 2, 3]
}
}Common Gotchas
Logging an entity can lazy-load the whole graph
override `toString` to print ids only, or do not log the entity.
Never put secrets in `toString`
tokens in debug logs become incidents.
Cyclic `toString` overflows the stack
break the cycle with an id.
Arrays do not override `toString`
use `Arrays.toString` or `List.of` for display.