DEV Community

Tohid Heshmati
Tohid Heshmati

Posted on • Updated on

toString or not to toString? This is the question

A "Hello World!" program which prints this sentence on the screen is the very first program almost any programmer writes.
It might have happened to you that you passed an Object to print or println methods and as a result have received a weird name@number answer.
In this example we pass an Object to println function without any addition.

public class ActionClass {
    public static void main(String[] args) {
        Book book = new Book("Odyssey","Homer");
        System.out.println(book);
    }

    private static class Book {
        String name;
        String author;

        public Book(String name, String author) {
            this.name = name;
            this.author = author;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The Result might appear as below:

Book@5a39699c
Enter fullscreen mode Exit fullscreen mode

Classes are known as reference variable. a reference variable is capable of storing the location of an object.
By going a little more in in detail we see that the reason is because of print function's implementation. By passing an Object to a print function the actual command that we write is:

System.out.println(book);
Enter fullscreen mode Exit fullscreen mode

But what Java sees and runs is:

System.out.println(book.toString());
Enter fullscreen mode Exit fullscreen mode

Hmmm. Now we have another Method to look at. Under the hood toString() method looks like this:

public String toString() {
        return this.getClass().getName() + "@" + Integer.toHexString(this.hashCode());
    }
Enter fullscreen mode Exit fullscreen mode

Aha, that explains the mysterious case of className@weirdNumber.

Any suggestion?
yes of course. By overriding the toString() method for our Object we can easily pass the object to print methods without turning them to strings.

@Override
        public String toString() {
            return "Book{" +
                    "name='" + name + '\'' +
                    ", author='" + author + '\'' +
                    '}';
        }
Enter fullscreen mode Exit fullscreen mode

After doing so the first code we wrote in this article will have a result as below without adding toString() method to it.

Book{name='Odyssey', author='Homer'}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)