toString(): print objects nicely
32 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)toString() turns an object into text. Java calls it whenever an object has to become a String, for example in System.out.println(s), so overriding it decides how your objects look when printed.
The default toString(): ClassName@hash
toString() is the Object method that returns a String describing an object. Java calls it whenever an object is printed or joined with text. The default gives the class name, @ and the hash code in hexadecimal, so classes override it to show their data.
You print a student and get Student@76ed5528, as you saw in Objects: instances of a class (opens in a new tab). That text comes from the toString() every class inherits from Object.
Example 1 · The default toString()
class Student { String name; int marks;
Student(String name, int marks) { this.name = name; this.marks = marks; }}
public class DefaultToStringDemo { public static void main(String[] args) { Student s = new Student("Aarav", 91); System.out.println(s); System.out.println(s.toString()); System.out.println(s.getClass().getSimpleName() + " " + s.hashCode()); }}Student@76ed5528 Student@76ed5528 Student 1995265320
What this code does
println(s)andprintln(s.toString())print the same thing: Java callstoString()for you.76ed5528is the hash code1995265320written in hexadecimal. Your numbers will differ.
Hexadecimal is base 16, written with the digits 0–9 and the letters a–f. The text names the class but shows no data, and the number can change from run to run. To print useful data, you override toString() like any other inherited method.
Override toString() to return your data
The header must match Object exactly: public String toString(), with @Override above it. Inside, build and return a String; never print.
Example 2 · Overriding toString()
class Student { String name; int marks;
Student(String name, int marks) { this.name = name; this.marks = marks; }
@Override public String toString() { return "Student[name=" + name + ", marks=" + marks + "]"; }}
public class ToStringDemo { public static void main(String[] args) { Student s = new Student("Aarav", 91); System.out.println(s); System.out.println("Topper: " + s); String line = s.toString(); System.out.println(line.length()); }}Student[name=Aarav, marks=91] Topper: Student[name=Aarav, marks=91] 29
What this code does
println(s)and"Topper: " + sboth call the overriddentoString()automatically.toString()returns a normalString, so you can store it and calllength()on it.
Example 3 · Mistake: a misspelled toString()
class Phone { String model;
Phone(String model) { this.model = model; }
@Override public String tostring() { return "Phone: " + model; }}
public class TypoDemo { public static void main(String[] args) { System.out.println(new Phone("Redmi")); }}TypoDemo.java:8: error: method does not override or implement a method from a supertype
@Override
^
1 errorWhat this code does
tostring(small s) is a brand-new method, so it overrides nothing. Without@Overridethis compiles and printsPhone@....- With
@Override, the compiler reports the typo at once. Fix: spell ittoString.
A common style is ClassName[field=value, ...]; a readable line such as Aarav (91 marks) is fine too. Without @Override, a typo like tostring() compiles as a brand-new method, and printing still shows Student@... with no warning.
Fix the error
Fix the toString() header
Read the error, then pick the line that fixes it.
Round 1 of 2
Printing a Train should show Train 12627.
Error
Train.java:4: error: toString() in Train cannot override toString() in Object
public void toString() { System.out.println("Train " + number); }
^
return type void is not compatible with StringtoString(): passwords, PINs and OTPs end up in logs and on screens.Java calls toString() for you
You rarely write .toString() yourself. println(obj), joining with + and Arrays.toString(arr) all call it, and they turn a null reference into the text null without crashing.
Example 4 · null references and arrays of objects
import java.util.Arrays;
class Student { String name; int marks;
Student(String name, int marks) { this.name = name; this.marks = marks; }
@Override public String toString() { return name + "(" + marks + ")"; }}
public class ArrayToStringDemo { public static void main(String[] args) { Student[] toppers = { new Student("Priya", 98), new Student("Rohan", 95), null }; System.out.println(Arrays.toString(toppers)); System.out.println("Rank 3: " + toppers[2]); System.out.println(toppers[2]); }}[Priya(98), Rohan(95), null] Rank 3: null null
What this code does
Arrays.toStringcallstoString()on each student and writesnullfor an empty slot.- Joining or printing a
nullreference gives the textnull. Onlytoppers[2].toString()would crash.
Calling s.toString() yourself on a null reference is different: there is no object, so it throws NullPointerException. Arrays do not override toString(), so print them with Arrays.toString, as in The Arrays utility class (opens in a new tab).
toString(): printing Day.MONDAY shows MONDAY.toString() in a class hierarchy
A child inherits its parent's toString(). It can override it again and reuse the parent's text with super.toString(), as in super.method() (opens in a new tab).
Example 5 · toString() in a hierarchy with super.toString()
class Person { String name; int age;
Person(String name, int age) { this.name = name; this.age = age; }
@Override public String toString() { return getClass().getSimpleName() + ": " + name + " (" + age + ")"; }}
class Student extends Person { int roll;
Student(String name, int age, int roll) { super(name, age); this.roll = roll; }
@Override public String toString() { return super.toString() + ", roll " + roll; }}
class Teacher extends Person { Teacher(String name, int age) { super(name, age); }}
public class HierarchyToStringDemo { public static void main(String[] args) { Person[] people = { new Person("Ravi", 45), new Student("Diya", 19, 12), new Teacher("Meera", 38) }; for (int i = 0; i < people.length; i++) { System.out.println(people[i]); } }}Person: Ravi (45) Student: Diya (19), roll 12 Teacher: Meera (38)
What this code does
Studentreuses the parent text withsuper.toString()and adds onlyroll.Teacherdoes not overridetoString(), so it inherits Person's.getClass().getSimpleName()still printsTeacher, the real class.
Inside the parent's toString(), getClass().getSimpleName() gives the real class, so one method prints Student or Teacher correctly. In a child, write super.toString(), never plain toString(): that calls itself again and again until StackOverflowError.
Predict the output
What gets printed?
Read the code and pick what it prints.
Round 1 of 3
Two seats joined with text.
Next step
Check your understanding
12 quick questions