Lesson 26 / 38
toString()
Override toString() for readable debug output and logging instead of the default ClassName@hashcode gibberish.
Why override it
The default toString() prints ClassName@hexHashCode — useless for debugging. System.out.println(obj), string concatenation, and most logging frameworks call toString() automatically, so a good one pays off everywhere.
A useful override
Keep it concise and include the fields that identify the object. Modern record types (Java 16+) generate a sensible toString(), equals() and hashCode() automatically.
@Override public String toString() {
return "Point[x=" + x + ", y=" + y + "]";
}
// Or skip all the boilerplate with a record:
record Point(int x, int y) {}
System.out.println(new Point(1, 2)); // Point[x=1, y=2]