Sub topic 9
Writing a useful `toString`
This chapter assumes you can write and compile Java classes, use fields and constructors, and understand method overriding. You should also know that every Java class inherits methods from java.lang.Object.
What `toString` does
toString returns a text representation of an object. Java calls it automatically when you concatenate an object with a string or pass it to System.out.println.
The default implementation from Object is usually not useful. It combines the class name with an identity-based hexadecimal value:
Order@6d311334That text can identify an object during debugging, but it does not show the object's data. Override toString when a readable representation will help you inspect logs, test failures, or debugger output.
public final class Order {
private final int id;
private final String customer;
private final boolean shipped;
public Order(int id, String customer, boolean shipped) {
this.id = id;
this.customer = customer;
this.shipped = shipped;
}
@Override
public String toString() {
return "Order{id=" + id
+ ", customer='" + customer + '\''
+ ", shipped=" + shipped
+ '}';
}
public static void main(String[] args) {
Order order = new Order(42, "Mina", false);
System.out.println(order);
System.out.println("Current order: " + order);
}
}The output is:
Order{id=42, customer='Mina', shipped=false}
Current order: Order{id=42, customer='Mina', shipped=false}The @Override annotation asks the compiler to verify that the method really overrides a superclass method. The method must have exactly this signature:
public String toString()A method such as toString(String format) is a different overload. Java will not use it automatically.
Choosing the representation
A useful representation normally includes the class name and the fields that explain the object's state. A consistent format makes logs easier to scan.
Include fields that help diagnose behavior, but omit implementation details that do not matter to readers. For example, a cached value might not belong in the output if it can be calculated from other fields.
Be careful with sensitive data. Do not print passwords, access tokens, private keys, full payment-card numbers, or personal data merely because a field exists. toString output often reaches logs, which may have a wider audience and longer retention than expected.
For nullable fields, string concatenation safely produces null. For more control, use String.valueOf(field) or a conditional expression. Avoid calling a nullable field's method directly inside toString, because a logging statement should not unexpectedly throw NullPointerException.
Collections and nested objects
Collections call each element's toString, so overriding the method improves output for lists, sets, and maps containing your class:
List<Order> orders = List.of(
new Order(1, "Ari", true),
new Order(2, "Jo", false)
);
System.out.println(orders);This prints readable objects only when Order overrides toString.
A toString implementation should be fast and side-effect free. It should not modify fields, perform network requests, query a database, or depend on mutable global state. Logging code may run while diagnosing a failure, so the method should remain reliable when the object is only partially initialized.
Exercise
Exercise
What is wrong with a toString method that returns only "Order" for every Order object, and what should a better implementation provide?
Show answer
It hides the object's state and makes different orders indistinguishable. A better implementation returns a readable class name and the relevant, non-sensitive fields.