Sub topic 9
Writing a useful toString
This chapter assumes you can write Java classes with fields and constructors, and that you have seen the default toString output ClassName@1b6d3586. It also assumes you know how equals and hashCode are overridden. Here you will decide what a good toString should print and avoid the bugs that appear when it prints too much.
What toString is for
toString returns a short, human-readable description of an object. The JDK documentation asks for a "concise but informative representation that is easy for a person to read" and recommends that every subclass override it.
Java calls toString implicitly in many places:
- String concatenation:
"Order: " + order System.out.println(obj)andString.valueOf(obj)- Logging frameworks that format message arguments
- The
toStringof collections, which call it on each element - Exception messages and debugger displays
Because so many callers use it, toString is a diagnostic tool, so its output is read mostly during debugging and in log files. A class without a useful toString forces every reader to inspect fields one by one.
A conventional format
Java has no mandatory format. The common convention is the class name followed by the field names and values:
import java.util.Arrays;
public class ToStringDemo {
static final class Customer {
private final String name;
private final String email;
private final String password;
private final int[] scores;
Customer(String name, String email, String password, int[] scores) {
this.name = name;
this.email = email;
this.password = password;
this.scores = scores.clone();
}
@Override
public String toString() {
return "Customer{name=" + name
+ ", email=" + email
+ ", scores=" + Arrays.toString(scores) + "}";
}
}
public static void main(String[] args) {
Customer c = new Customer("Ada", null, "s3cret", new int[] {90, 85});
System.out.println(c);
// Customer{name=Ada, email=null, scores=[90, 85]}
}
}Three details in this example matter:
- The
passwordfield is left out on purpose. emailisnull, and concatenation prints it as the textnull. Callingemail.toString()directly would throw aNullPointerException.scoresis printed withArrays.toString. Without it, you would get the array's default form, such as[I@6d06d69c.
The @Override annotation is not optional in practice. Without it, a typo such as tostring() compiles and is silently never called.
What to include and what to leave out
Print the state that identifies the object and explains its behavior. Leave out anything that is sensitive, huge, or dangerous to read.
| Field kind | Recommendation | Reason |
|---|---|---|
| Identifiers and key attributes | Include | They are what you look for in a log. |
| Passwords, tokens, card numbers | Never include | Logs are copied, stored, and shared. |
| Personal data (email, address) | Include only if policy allows | Privacy rules often cover log files. |
| Large collections or buffers | Print the size or a prefix | A million-element list makes one log line unreadable. |
| References to other entities | Print an id or name only | Printing the whole object can recurse (see below). |
| Lazy-loaded or remote data | Leave out | `toString` should not trigger database or network calls. |
A rule of thumb: print the fields that equals compares, plus any that help you diagnose problems, minus anything sensitive.
Keep toString free of side effects
toString can be called at any moment, including from a debugger or a logging thread. It should therefore:
- Only read state and never change it.
- Never throw an exception. A failing
toStringcan hide the real error that you were trying to log. - Never block on I/O, locks, or lazy initialization.
- Be reasonably cheap. Logging calls that build strings that are later discarded still cost time.
Cycles cause StackOverflowError
If object A prints object B and B prints A, the calls never end. This is the most common serious toString bug, and it appears with parent-child relationships.
import java.util.ArrayList;
import java.util.List;
public class CycleDemo {
static final class Team {
final String name;
final List<Player> players = new ArrayList<>();
Team(String name) { this.name = name; }
@Override
public String toString() {
return "Team{name=" + name + ", players=" + players + "}";
}
}
static final class Player {
final String name;
final Team team;
Player(String name, Team team) {
this.name = name;
this.team = team;
team.players.add(this);
}
@Override
public String toString() {
// Printing "team=" + team here would call Team.toString,
// which prints players, which calls Player.toString again.
return "Player{name=" + name + ", team=" + team.name + "}";
}
}
public static void main(String[] args) {
Team t = new Team("Reds");
new Player("Kim", t);
new Player("Lee", t);
System.out.println(t);
// Team{name=Reds, players=[Player{name=Kim, team=Reds}, Player{name=Lee, team=Reds}]}
}
}The fix is to break the cycle on one side. Here Player prints only the team's name, so the chain ends. The same cycle problem affects equals and hashCode, so the same fix usually applies to all three.
The JDK handles one special case itself. A collection that contains itself prints (this Collection) for that element instead of recursing. Your own classes get no such protection.
Null safety
String concatenation and String.valueOf(Object) both turn null into the text "null". Use them rather than calling toString() on a field that might be null.
Object maybe = null;
String a = "value=" + maybe; // "value=null"
String b = String.valueOf(maybe); // "null"
String c = java.util.Objects.toString(maybe, "none"); // "none"
// maybe.toString() would throw NullPointerExceptionObjects.toString(obj, defaultValue) is useful when the word null is not what you want to show.
Building the string
For a few fields, concatenation with + is fine. The compiler turns it into efficient code. Other options are:
String.formatorformatted, which are good for controlling number formats but slower.StringBuilder, which is useful when you append inside a loop.StringJoiner, which handles separators and prefix and suffix for you.
import java.util.StringJoiner;
public class JoinerDemo {
public static void main(String[] args) {
StringJoiner sj = new StringJoiner(", ", "Order{", "}");
sj.add("id=42");
sj.add("total=" + String.format("%.2f", 19.5));
System.out.println(sj); // Order{id=42, total=19.50}
}
}Fixed formatting of a double, as with %.2f, is a deliberate choice. String.valueOf(double) can print values such as 1.0E10 or 0.30000000000000004, which is accurate but sometimes confusing to a reader.
Subclasses and inheritance
If a parent class already has a good toString, a subclass can reuse it. super.toString() gives you the parent's text, but if the parent never overrode it, you get the Object default with its hash code. Check before relying on it.
A common pattern is to put the class name in via getClass().getSimpleName() so that subclasses print their own name without overriding the method:
@Override
public String toString() {
return getClass().getSimpleName() + "{id=" + id + "}";
}Note that anonymous classes return an empty simple name.
Do not parse toString
Treat the output as a message for people. Do not build program logic that splits or matches it. The format can change at any time, and other code will break silently. If callers need the data, expose getters or a dedicated method such as toJson() or format(). If you do commit to a precise format, as BigInteger and Instant do, document it in the Javadoc and provide a matching factory such as parse or valueOf.
Records
A record generates toString for you. The output uses square brackets and lists the components in declaration order:
public class RecordDemo {
record Point(int x, int y) {}
public static void main(String[] args) {
System.out.println(new Point(1, 2)); // Point[x=1, y=2]
}
}You can still override it, for example to hide a sensitive component:
record Login(String user, String password) {
@Override
public String toString() {
return "Login[user=" + user + ", password=****]";
}
}Without that override, a record would print the password in every log line, so check records for sensitive components just as you would for classes.
Common mistakes
- Leaving the default
toString, which printsClassName@hexand says nothing about state. - Printing arrays directly instead of with
Arrays.toStringorArrays.deepToStringfor nested arrays. - Including secrets.
- Printing both sides of a bidirectional relationship.
- Calling
toString()on a nullable field. - Using the output as data.
Exercise
A class Node has fields String label and Node next, and its toString is "Node{label=" + label + ", next=" + next + "}". What happens when you print a Node whose next field points back to itself, and how do you fix it?
Show answer
Node.toString calls next.toString(), which is the same method on the same object, so the calls never end and the JVM throws a StackOverflowError. Fix it by not printing the full next node, for example by printing only its label (guarding for null, such as next == null ? "null" : next.label), so that the chain stops after one step.
Exercise
Why is "email=" + email safer than "email=" + email.toString() inside a toString method when email may be null?
Show answer
String concatenation converts a null reference to the text "null" through String.valueOf, so it never throws. Calling email.toString() on a null reference throws a NullPointerException, which would break the logging or debugging call that was using toString.