toString or not to toString? This is the question

A “Hello World!” program witch 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;
    }
    }
    }

The Result might appear as below:

  • Book@5a39699c

📷

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);

But what Java sees and runs is:

  • System.out.println(book.toString());

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());
    }

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 + '\'' +
    '}';
    }

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'}

you may also want to read the same in Medium or dev.to