toString() Method in Java
Print an object of your own class and you'll see something like Student@1b6d3586. That's the default toString() inherited from Object: the class name, an @, and the hash code in hex. It's correct but useless for a human. Overriding toString() gives your objects a readable text form, which makes printing, logging and debugging far easier.
Default vs Overridden
import java.util.Arrays;
import java.util.List;
public class Report {
static class Student {
private final String name;
private final int marks;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
@Override
public String toString() {
return "Student[name=" + name + ", marks=" + marks + "]";
}
}
public static void main(String[] args) {
Student s = new Student("Advitha", 92);
System.out.println(s);
System.out.println("Topper: " + s);
List<Student> list = List.of(s, new Student("Navika", 88));
System.out.println(list);
int[] scores = {92, 88, 75};
System.out.println(Arrays.toString(scores));
}
}Student[name=Advitha, marks=92]
Topper: Student[name=Advitha, marks=92]
[Student[name=Advitha, marks=92], Student[name=Navika, marks=88]]
[92, 88, 75]How it works
toString()is overridden to return the fields in a readable form. It must bepublic, becauseObject.toString()is public.System.out.println(s)callss.toString()for you.- String concatenation (
"Topper: " + s) calls it too. - A
List's owntoString()callstoString()on each element. - Arrays don't override
toString(). Printingscoresdirectly would show something like[I@4e25154f;Arrays.toStringgives[92, 88, 75].
Without the override, the first line would print something like this (the hex part changes from run to run):
Report$Student@1b6d3586Where Java Calls toString()
| Situation | Example |
|---|---|
| Printing | System.out.println(obj), printf("%s", obj) |
| String concatenation | "Total: " + obj |
String.valueOf(obj) | Returns "null" for null, otherwise obj.toString() |
| Collections and maps | list.toString(), map.toString() call it on each element |
| Debuggers and logs | IDEs show toString() in variable views; loggers print it |
Writing a Good toString()
- Include the fields that identify the object and help debugging.
- Leave out secrets: passwords, tokens, full card or Aadhaar numbers end up in logs.
- Keep it fast and free of side effects; debuggers call it often.
- Don't make other code parse it; it's for humans.
Common Mistakes
Printing an array directly. You get [I@.... Use Arrays.toString, or Arrays.deepToString for 2D arrays.
Writing public String tostring(). The lowercase s creates a new method; @Override would catch it.
Calling obj.toString() on a possibly null reference. It throws NullPointerException; String.valueOf(obj) or concatenation print null instead.
Interview Corner
What does the default toString() return?
getClass().getName() + "@" + Integer.toHexString(hashCode()), for example Student@1b6d3586: the class name and the object's hash code in hexadecimal. It's not meaningful to humans, so classes usually override it.
When is toString() called implicitly?
When an object is printed with print, println or printf("%s"), when it's concatenated with a string, when String.valueOf is called on it, and when collections build their own text form from their elements.
Practice
- Easy: Override
toString()in aBookclass with title, author and price, and print a book. - Harder: Override
toString()in aBankAccountso it shows the holder and balance, but masks the account number to its last four digits, likeXXXXXX4321.
Key Takeaways
Was this tutorial helpful?