Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

What does Object.toString return by default, and what makes a good toString override? What should never be in it?

By default, Object.toString returns the class name, an @ sign and the object's hash code in hexadecimal, such as com.acme.Order@1b6d3586, which tells us almost nothing. A good override shows the fields that help debugging in a readable form, as records do automatically. It must never contain passwords, tokens, secrets or personal data, because toString output ends up in logs and exception messages; it should avoid expensive or recursive work such as printing lazy JPA collections; and no code should parse it.

Why this question is asked

toString looks like the least important method on a class, yet it is the one that decides what we see at three in the morning when reading logs and stack traces. It is also, surprisingly often, how passwords end up in log files. Interviewers ask about it because the answer shows whether we think about where our objects' text goes. In this answer, we will see what the default toString returns and why, what makes a useful override, what must never be in it and why, how to keep it cheap and safe, and why its output is not an API.

1What the Default toString Returns

Every class inherits toString from Object. The default implementation returns the class's fully qualified name, an @ character and the result of hashCode() written in hexadecimal.

Java
class Order { long id = 42; String status = "PAID"; }
Order o = new Order();
System.out.println(o); // com.acme.Order@1b6d3586 (the hex part varies)
// what Object.toString does:
o.getClass().getName() + "@" + Integer.toHexString(o.hashCode()); // the same string

The hexadecimal part is the identity hash code, not a memory address, even though it is often described that way. It is useful only to tell two objects apart in one run. Notice that println calls toString for us, and so does string concatenation and most logging frameworks, which is exactly why toString matters: our objects are turned into text in many places we never wrote explicitly.

2What Makes a Good toString

A good toString answers the question a developer has when reading a log line: which object is this, and what state is it in? That usually means the class's short name, its identifier and a few fields that explain its state, in a readable, compact form. Records generate exactly this kind of output from their components.

Java
record Order(long id, String status, long totalCents) {}
System.out.println(new Order(42, "PAID", 1500)); // Order[id=42, status=PAID, totalCents=1500]
// A hand-written equivalent for a normal class
@Override public String toString() {
return "Order[id=" + id + ", status=" + status + ", lines=" + lines.size() + "]";
}

Notice that the hand-written version prints the number of lines, not the lines themselves. Printing a summary of a collection keeps the output short and avoids pulling in large or nested objects. The goal is debugging value per character, not completeness.

3What Must Never Be in It: Secrets and Personal Data

toString output travels far. It is written to application logs, included in exception messages, shown in error pages in development, copied into monitoring tools and kept for months. Anything it prints should be treated as published to everyone who can read those systems. So it must never include passwords, API keys, access tokens, session IDs, card numbers or personal data such as email addresses, phone numbers or national IDs.

Java
record LoginRequest(String username, String password) {}
log.warn("login failed: {}", request);
// login failed: LoginRequest[username=ana, password=hunter2] <- a password in the logs
record LoginRequest(String username, String password) {
@Override public String toString() {
return "LoginRequest[username=" + username + ", password=***]";
}
}
// login failed: LoginRequest[username=ana, password=***]
What belongs in toString
IncludeLeave outWhy
Class name and IDPasswords, tokens, keysLogs are read by many people and kept long
Status and key fieldsEmails, phones, card numbersPersonal data in logs is a compliance risk
Collection sizesLazy or large collectionsCan trigger queries or huge output
IDs of related objectsRelated objects themselvesBidirectional links recurse
Show enough to identify the object and its state, nothing more.

The danger is greatest with generated toString methods. Records, Lombok's @ToString and IDE templates print every field by default, so adding a password or token field to such a class silently adds it to the logs. Any class holding secrets should override toString explicitly, or hold the secret in a wrapper type whose own toString prints a mask.

4Keeping It Cheap and Non-Recursive

toString is called implicitly, often in logging and in debuggers, so it must be cheap and must not change anything. A toString that touches a lazy JPA collection triggers a database query each time an object is logged, or throws LazyInitializationException when no session is open. A toString that prints another object which prints this one back, as in a bidirectional parent and child, recurses until StackOverflowError.

The safe pattern is to print only simple fields and the IDs of related objects, never the related objects themselves. A toString should also never throw: if a field may be null, string concatenation handles it, printing "null", which is fine.

5Do Not Parse toString Output

Because toString is so convenient, some code ends up reading it back: splitting a string at commas to get an ID, or comparing toString results in a test. That couples the code to a format that was written for humans and may change at any time. The Javadoc for Record.toString says outright that its exact format is not specified and may change.

If some code needs a value, it should call the accessor. If a class needs a stable text form, for an identifier or a file format, it should provide a separately named method, such as format() or toIsoString(), and document it. When toString's format is not meant to be stable, saying so in the Javadoc stops others relying on it.

6Follow-up questions

Is the number after @ the memory address?

No. It is the identity hash code in hexadecimal. In HotSpot it is generated once, when first requested, and stored in the object header, and objects can move in memory during garbage collection while keeping the same identity hash code. If a class overrides hashCode, the default toString shows that value instead.

Should toString use String.format or concatenation?

Either is fine for readability. Concatenation is usually faster, and modern Java compiles it efficiently. What matters more is avoiding expensive work, such as formatting large collections, because toString may be called on every log line.

Do logging frameworks call toString if the level is disabled?

With parameterised messages such as log.debug("order {}", order), SLF4J and Log4j 2 only format the message if the level is enabled, so toString is not called. String concatenation in the call, as in log.debug("order " + order), runs toString every time, even when the line is not logged.

7Conclusion

In this answer, we saw that Object.toString returns the class name, @ and the hexadecimal hash code, as in com.acme.Order@1b6d3586. A good override, like a record's, shows the ID and the fields that explain the state, in a compact, readable form. It must never contain secrets or personal data, because its output lands in logs and exception messages; it must stay cheap and avoid lazy or bidirectional associations; and other code must never parse it.

What to say in the interviewAbout 70 seconds aloud

Open with

By default, toString comes from Object and returns the fully qualified class name, an @ sign and the hash code in hex, something like com.acme.Order@1b6d3586, which only tells you that two objects are different.

Then, if they want more

A good override shows what you need when debugging: the class name, the ID and the few fields that explain the state, compactly. Records do that automatically, for example Order[id=42, status=PAID, totalCents=1500]. For collections, I print the size or the IDs, not the elements.

What must never be in toString is anything sensitive: passwords, tokens, API keys, card numbers or personal data like emails, because toString output ends up in logs, exception messages and monitoring tools, and generated toString methods, records and Lombok included, print every field unless you override them.

I also keep toString cheap and side-effect free, so no lazy JPA collections, which can trigger queries or LazyInitializationException, and no printing of a parent that prints its children back, which recurses into StackOverflowError. Finally, toString is for humans, so no code should parse it; if something needs a stable text form, it gets its own documented method.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What does Object.toString return by default, and what makes a good toString override?...": https://scrivio-interview-library.netlify.app/java/object-contracts/99160b2338/