toString() Override in Java
beginner· OOP · Object Class
Problem
Every object inherits a default toString() from Object that prints the class name and a hashcode; overriding it lets an object describe itself in whatever format actually makes sense.
Create a Book class that overrides toString() to print its title and author in a readable format.
Input
new Book("Java Basics", "J. Smith")
Output
Java Basics by J. Smith
Java Program
Java
public class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
@Override
public String toString() {
return title + " by " + author; // replaces the default ClassName@hash format
}
public static void main(String[] args) {
Book book = new Book("Java Basics", "J. Smith");
System.out.println(book);
}
}Output
Java Basics by J. Smith
Core Logic
Overriding toString() to build a readable string from an object's own fields replaces Java's default identity-based format with something actually meaningful.
How It Works
- 1
class Bookstores atitleandauthoras fields. - 2
@Override public String toString()replaces the inherited version with one that returnstitle + " by " + author. - 3
System.out.println(book)callstoString()automatically whenever an object is printed or concatenated into a string. - 4Without this override, printing the object would instead show something like
Book@1b6d3586— the class name followed by a hash code, which says nothing about the book itself.
Printing a Book built from "Java Basics" and "J. Smith" produces
"Java Basics by J. Smith", not the default identity string.💡
Key Point: toString() is called implicitly any time an object is printed or added to a String with +, which is exactly why overriding it pays off — every future print of this object automatically benefits, with no explicit formatting call needed at each site.
Key Concepts
@OverridetoString()Object class