CKTIS / Java
Overriding Object.toString()
Give an object a readable description and see how `println(Object)` prints it without an explicit call to `toString()`.
Version: Java SE 21
Syntax
@Override
public String toString() {
return "Readable object description";
}An Object.toString override lets a class describe an instance in a short, readable string. Declare the public, no-argument instance method public String toString() and return the text rather than printing it. Use @Override to catch mistakes at compile time: toString(String prefix) is an overload, not an override.
The implementation in Object returns the object's runtime class name, @, and the result of hashCode() in unsigned hexadecimal. This is not a memory address or a unique identifier.
When task is declared as Object, System.out.println(task) selects println(Object). That overload uses String.valueOf(Object), which calls the runtime object's toString() implementation for a non-null argument. If the reference is null, println(Object) prints the text null, while a direct task.toString() call throws NullPointerException.
Return a non-null string that includes only useful, non-sensitive fields. Don't change the object's state or expose passwords or tokens: the description can end up in logs. Don't rely on it as a stable format for parsing or storage.
Examples
public class Main {
private static final class Task {
private final String title;
private final boolean done;
Task(String title, boolean done) {
this.title = title;
this.done = done;
}
@Override
public String toString() {
return "Task{title='" + title + "', done=" + done + "}";
}
}
public static void main(String[] args) {
Object task = new Task("Review notes", false);
System.out.println(task.toString());
System.out.println(task);
Object missing = null;
System.out.println(missing);
}
}Result
Task{title='Review notes', done=false}
Task{title='Review notes', done=false}
null
The first two lines match: the direct call and `println(Object)` both use the `Task` implementation. The third line shows how `null` is handled without calling `toString()`.
Related lessons
- Java · Lesson 26 · Intermediate · Version: 2
- Java · Lesson 27 · Intermediate · Version: 2
- Java · Lesson 32 · Intermediate · Version: 2