Sub topic 8
What toString is for and what the default prints
This chapter assumes you can write basic Java classes, know that Object is the root of every class, and have used List and Map from java.util. Here you will see what toString is meant for, what Object prints when you don't override it, and where the JVM calls it for you.
What toString is for
toString returns a String that describes an object for a human reader. The Javadoc for Object.toString asks for "a concise but informative representation that is easy for a person to read" and recommends that every subclass override it.
Typical readers are:
- A developer looking at log output.
- A developer reading a failed test message.
- A developer inspecting a variable in a debugger.
- A user looking at a simple console tool.
The method is a diagnostic aid. It is not a serialization format, and other code should not parse its output unless you document the format as part of your API.
What the default prints
If a class does not override toString, it inherits the version from Object. That version is defined as:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}The result has three parts:
- The fully qualified runtime class name, from
getClass().getName(). - An
@character. - The hash code as unsigned hexadecimal digits.
The following program shows the default output for several kinds of objects:
import java.util.Arrays;
public class DefaultToString {
static class Plain {}
static class Tagged {
@Override
public int hashCode() {
return 255;
}
}
public static void main(String[] args) {
Object plain = new Plain();
System.out.println(plain);
System.out.println(plain.getClass().getName()
+ "@" + Integer.toHexString(plain.hashCode()));
System.out.println(new Tagged());
int[] numbers = {1, 2, 3};
System.out.println(numbers);
System.out.println(Arrays.toString(numbers));
Runnable task = () -> {};
System.out.println(task);
}
}A run prints something like this. The hexadecimal values will differ on your machine:
DefaultToString$Plain@1b6d3586
DefaultToString$Plain@1b6d3586
DefaultToString$Tagged@ff
[I@4554617c
[1, 2, 3]
DefaultToString$$Lambda/0x000001e5c1003200@74a14482Each line shows a rule:
- Nested classes use
$between the outer and inner names, so you seeDefaultToString$Plain. Anonymous classes get numbers, such asOuter$1. - Arrays do not override
toString. The name[Iis the JVM's internal name forint[]. UseArrays.toStringfor one-dimensional arrays andArrays.deepToStringfor nested ones. - Lambdas print a generated class name. The exact text depends on the JVM version.
- The hash part is not a memory address, even though people often describe it that way. The default
hashCodeis an identity hash that the JVM generates. In HotSpot it is typically a pseudo-random number assigned the first time it is requested.
The default depends on hashCode
Tagged overrides hashCode and nothing else, yet its default toString printed @ff. The reason is that Object.toString calls hashCode(), which is a virtual call. If you override hashCode, the default toString uses your value.
This has two practical consequences:
- Two objects with the same printed default string may be different objects. Hash codes can collide, so the string is not an identity check.
- Two distinct objects that are equal and share a hash code print identically. This is a hint that the output is not a reliable identifier.
Where toString gets called
You rarely call toString by hand. Many parts of Java call it for you, which is why a missing override shows up in so many places.
| Call site | Behavior |
|---|---|
| `"p = " + p` | The compiler turns this into string building that converts `p` with `String.valueOf`. |
| `System.out.println(p)` | The `Object` overload calls `String.valueOf(p)`. |
| `String.format("%s", p)` | `%s` converts the argument with `toString`, or prints `null`. |
| `list.toString()` | `AbstractCollection` calls `String.valueOf` on each element, so one bad element `toString` affects the whole list output. |
| `map.toString()` | Each key and each value is converted the same way, in `key=value` form. |
The null handling is the main difference from calling the method directly:
public class NullSafety {
public static void main(String[] args) {
Object missing = null;
System.out.println("value: " + missing); // value: null
System.out.println(String.valueOf(missing)); // null
try {
System.out.println(missing.toString());
} catch (NullPointerException e) {
System.out.println("direct call throws NullPointerException");
}
}
}Implicit conversion is safe for null references. Calling .toString() on a null reference throws a NullPointerException. In your own code, prefer String.valueOf(x) or Objects.toString(x) when x might be null.
A first useful override
An override should show the class name and the fields that identify the object. A common layout is ClassName{field=value, ...}.
import java.util.List;
import java.util.Map;
final class Point {
private final int x;
private final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Point{x=" + x + ", y=" + y + "}";
}
}
public class ToStringDemo {
public static void main(String[] args) {
Point p = new Point(1, 2);
System.out.println(p);
System.out.println(List.of(p, new Point(3, 4)));
System.out.println(Map.of("origin", new Point(0, 0)));
}
}Output:
Point{x=1, y=2}
[Point{x=1, y=2}, Point{x=3, y=4}]
{origin=Point{x=0, y=0}}One override improves every place from the table above. The list and map print readably without any extra code. This chapter only introduces the idea. A later chapter on writing a useful toString covers design choices in detail, such as which fields to include.
Rules of thumb for the default and for overrides
Keep these points in mind when you rely on toString or write one:
- Do not change state. The method is called by debuggers and loggers, often at unexpected times. Mutating fields inside
toStringcreates bugs that appear only under a debugger. - Keep it cheap. Do not query a database or walk a huge structure. A logger may call it for a message that is filtered out later, so a slow
toStringslows the application. - Do not throw. A
toStringthat throws can hide the original error, because the exception is raised while the error message is being built. - Watch for cycles. If
Parent.toStringprints its children andChild.toStringprints its parent, printing either one recurses until aStackOverflowError. Print an identifier for the back reference instead of the whole object. - Leave out secrets. Passwords, tokens, and personal data end up in logs because someone printed the object. Omit these fields or mask them.
- Document it only if callers depend on it. If you promise a format, you cannot change it freely. If you do not, say nothing, and callers should treat the text as informal.
Common mistakes
- Printing an array directly.
System.out.println(array)prints[I@...and not the contents. UseArrays.toString. - Expecting the default to show field values. The default never shows fields. If your log line looks like
Order@6d06d69c, the class needs an override. - Calling
toStringon a possibly null reference. UseString.valueOforObjects.toString. - Parsing
toStringoutput. The text can change when a field is added or renamed. Expose real accessors or a dedicated format instead. - Forgetting that subclass output differs.
getClass().getName()is the runtime class, so an inherited default shows the subclass name even when the method is declared in a parent.
Exercise
A class Session overrides hashCode to return 42 but does not override toString. What does new Session() print when passed to System.out.println, assuming the class is a top-level class in the default package, and why?
Show answer
It prints Session@2a. The default Object.toString builds the text as getClass().getName() + "@" + Integer.toHexString(hashCode()). Because hashCode() is a virtual call, the overridden version returns 42, and 42 in hexadecimal is 2a.
Exercise
What is the difference between String.valueOf(obj) and obj.toString() when obj is null, and which one does string concatenation use?
Show answer
String.valueOf(obj) returns the text "null", while obj.toString() throws a NullPointerException. String concatenation, println, and %s formatting convert through the String.valueOf path, so they print null instead of failing.
Exercise
Why does printing new int[] {1, 2, 3} with System.out.println give output like [I@4554617c, and how do you print the contents?
Show answer
Arrays do not override toString, so they use the Object default. It prints the JVM's internal class name [I for int[], then @ and the identity hash in hexadecimal. Use Arrays.toString(array) for a one-dimensional array, or Arrays.deepToString(array) for nested arrays.