Task 5 of 9 · 0 solved · 9 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

4.5 Static and toString — toString

Lesson

A readable text form for an object

A toString method returns a String that describes an object. Java calls it automatically whenever an object is printed or joined to a string — so System.out.println(obj) shows your text instead of a cryptic default. You write it as public String toString() and return whatever text you want.


Worked example

class Point {
    int x;
    int y;

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

Point p = new Point();
p.x = 3;
p.y = 4;
System.out.println(p);   // (3, 4)  — println uses toString

▶ Try it: println(p) automatically calls toString(). Run this, then change x and y and re-run.



What does toString do?


Point's toString returns "(" + x + ", " + y + ")". For x = 3 and y = 4, type what System.out.println(p) prints:


What is the correct header for a toString method?


True or false?