AI Hints
Home›Java Tutorial›Access Modifiers, Getters and Setters, and toString
Java · Lesson 72 of 120

toString

How an object prints.

⏱ 2 min read▶ Video at 1:30:35🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

What happens when you print an object? By default, you get something unreadable. A method called to string fixes that.

  • Print an object?
  • Unreadable by default
  • toString fixes it

The default

Point has two private fields, and nothing else. Printing it calls a built in to string method. Run it. Point, an at sign, and a strange code. Not very helpful.

Main.javajava
public class Main {
    public static void main(String[] args) {
        Point p = new Point(3, 4);
        System.out.println(p);
    }
}
Output
Point@251a69d7
Also uses Point.java
public class Point {
    private int x, y;
    public Point(int x, int y) { this.x = x; this.y = y; }
}

Writing toString

We add our own to string method. It returns a nice, readable string. At override tells Java we're replacing the built in version. We'll learn more about override, in the next module.

Main.javajava
public class Point {
    private int x, y;
    public Point(int x, int y) { this.x = x; this.y = y; }

    @Override
    public String toString() {
        return "Point(" + x + ", " + y + ")";
    }
}

Printing nicely

Now, println uses our to string. Joining an object into a string uses it too. Run it. Point three, four, in both lines.

Main.javajava
public class Main {
    public static void main(String[] args) {
        Point p = new Point(3, 4);
        System.out.println(p);
        System.out.println("Start at " + p);
    }
}
Output
Point(3, 4)
Start at Point(3, 4)
Also uses Point.java
public class Point {
    private int x, y;
    public Point(int x, int y) { this.x = x; this.y = y; }

    @Override
    public String toString() {
        return "Point(" + x + ", " + y + ")";
    }
}

Summary

Override to string, to control how your objects print. Println, and joining with plus, both use it. That's the end of module eight. Next module, object oriented programming.

Key takeaways
  • toString()
  • @Override
  • Readable objects
Next up: Encapsulation — hide the details