Java toString method

The toString method

The Java toString is a String class method. This method returns an object’s string representation.

A few points about the toString method are:

  • The toString method returns a string.
  • The string contains the name of the class of object.
  • Returned string also contains an ‘@’ sign along with the unsigned hexadecimal representation of the hash code of the object.
  • It is recommended that all subclasses override this method.
  • By overriding, the value of the object can be returned.

To make it clear, see the example below and especially output with and without the toString method.

Example without toString method

See this example online

The output is:


As you can see, this is not understandable output with hash code without using the toString method.

To get the value of the object, let us use the toString method as follows:

Example with Java toString method

See the example online

The output is:

Name is:Mike age is:30

As you can see, this outputs understandable result by using the toString Java.

Related reading: Java string