toString
- Java course
- Intermediate
- Lesson 5/116
- 4 min
Learn object representation with toString.
The toString method
When you print an object directly with System.out.println, Java shows the class name and a number. To see a meaningful text instead, you override the toString method. The method must return a String.
Example: public String toString() { return "Book: " + title; }. After adding this method, calling System.out.println(book) automatically prints the text returned by toString. Converting an object to a string is now under your control; it helps a lot in debugging and logging.
Automatic invocation
When you put an object directly inside println, Java runs the toString method without you calling it. The same applies to string concatenation: "Result: " + object automatically uses toString.
Example: System.out.println(book); produces the same output as calling book.toString(). If toString is not defined, the default behavior shows the class name and memory location. That is why writing toString in your own classes is a good habit; it keeps the output readable.
Practice Add toString to the Book class
Define a class named Book with String title and int pages fields. Add a public String toString() method; its body returns title + " - " + pages + " pages". In main create a Book instance, assign values to the fields and print the instance with println.
Starter code
// Define the Book class
// Add a toString method
// Instantiate and print in mainSample solution
class Book {
String title;
int pages;
public String toString() {
return title + " - " + pages + " pages";
}
public static void main(String[] args) {
Book b = new Book();
b.title = "Java";
b.pages = 300;
System.out.println(b);
}
}Expected output
Java - 300 pages
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the return type of the toString method?
- Object
- int
- String Correct answer
- void
Explanation: String — toString returns a string.
2 Match the toString parts
| Term | Meaning |
|---|---|
public |
Access modifier |
String |
Return type |
toString |
Method name |
return |
Return statement |
3 Complete the toString method
public String toString() {
return "Book: " + ____;
}
public String toString() {
return "Book: " + title;
}
Explanation: The title field is returned to form a meaningful string.