Java: toString Method

Before we begin discussing the toString method, it is important to have a basic understanding of the class hierarchy in Java. All classes in Java inherit from the Object class; the Object class is at the root of the class hierarchy in Java.

Therefore, every existing built-in class or any class that is defined in Java has the Object as their parent (superclass) and has access to the methods in the Object class. If you are interested in learning more about the Object class, have a look at the official documentation. The toString method is one of the methods defined in the Object class and all classes inherently have this method.

Ideally, the toString method is to be used to return the textual representation of the object in string format. It is advisable to override this method in your classes to provide information about the object. For example, if you had a User class; your toString method would look something like this:

And in our main method, we create an object of the User class and if we pass that object as an argument directly into our print statement as such:

The output in the console is:

UserName: Anton
ID: 1
Premium: true

Voila! Our string method returned a textual representation of our object. If you are unfamiliar with the StringBuilder class, check out my article on it!

Now, you may wonder what happens if we don’t override the toString method in our User class; let’s find out! As you can see in Fig.3 below, I’ve removed the toString method from the User class.

When we call our main method again (see figure 2.1), the output in the console is the following:

User@7d417077

This is the default toString method return value of the user1 object we created. This is because the toString method in the the Object class looks like this:

When we do not override the toString method, it defaults to using the toString method that is defined in the Object class and as a result we get the name of our class, followed by the ‘at sign’ and the hexadecimal representation of the hash code (integer value that is associated with each object in Java) of the object.

Hope you learned something!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store