Skip to lesson

toString(): print objects nicely

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()

DefaultToStringDemo.javaJava
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());    }}
Sample output
Student@76ed5528
Student@76ed5528
Student 1995265320

What this code does

  • println(s) and println(s.toString()) print the same thing: Java calls toString() for you.
  • 76ed5528 is the hash code 1995265320 written 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()

ToStringDemo.javaJava
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());    }}
Output
Student[name=Aarav, marks=91]
Topper: Student[name=Aarav, marks=91]
29

What this code does

  • println(s) and "Topper: " + s both call the overridden toString() automatically.
  • toString() returns a normal String, so you can store it and call length() on it.

Example 3 · Mistake: a misspelled toString()

TypoDemo.javaJava
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"));    }}
Sample compiler output
TypoDemo.java:8: error: method does not override or implement a method from a supertype
    @Override
    ^
1 error

What this code does

  • tostring (small s) is a brand-new method, so it overrides nothing. Without @Override this compiles and prints Phone@....
  • With @Override, the compiler reports the typo at once. Fix: spell it toString.

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.

class Train {
int number = 12627;
public void toString() { System.out.println("Train " + number); }
}

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 String
Leave secrets out of toString(): 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

ArrayToStringDemo.javaJava
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]);    }}
Output
[Priya(98), Rohan(95), null]
Rank 3: null
null

What this code does

  • Arrays.toString calls toString() on each student and writes null for an empty slot.
  • Joining or printing a null reference gives the text null. Only toppers[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).

Enum constants already override 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()

HierarchyToStringDemo.javaJava
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]);        }    }}
Output
Person: Ravi (45)
Student: Diya (19), roll 12
Teacher: Meera (38)

What this code does

  • Student reuses the parent text with super.toString() and adds only roll.
  • Teacher does not override toString(), so it inherits Person's. getClass().getSimpleName() still prints Teacher, 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.

class Seat {
int no;
Seat(int no) { this.no = no; }
@Override
public String toString() { return "S" + no; }
}
public class SeatDemo {
public static void main(String[] args) {
Seat a = new Seat(4);
Seat b = new Seat(5);
System.out.println("Seats: " + a + b);
System.out.println(a + " and " + b);
}
}

Next step

Check your understanding

12 quick questions