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.
toString
String
System.out.println(obj)
public String toString()
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.
println(p)
toString()
x
y
What does toString do?
Point's toString returns "(" + x + ", " + y + ")". For x = 3 and y = 4, type what System.out.println(p) prints:
Point
"(" + x + ", " + y + ")"
x = 3
y = 4
System.out.println(p)
What is the correct header for a toString method?
True or false?