Java Object toString()

The toString() method converts the object into a string and returns it.

Example


Syntax of Object toString()

The syntax of the toString() method is:

object.toString()

toString() Parameters

The toString() method does not take any parameters.


toString() Return Values

  • returns the textual representation of the object

Note: The returned string consists of the name of the class, the at-sign character (@), and the hash code of the object in hexadecimal representation.


Example 1: Java Object toString()

In the above examples, we have created objects of the Object class. We have used the toString() method to convert the object into the string.

Notice the output,

java.lang.Object@6a6824be

Here,

  • java.lang.Object - class name
  • @ - the at-sign
  • 6a6824be - hashcode of object in hexadecimal format

Note: The Object class is the superclass for all the classes in Java. Hence, every class and arrays can implement the toString() method.


Example 2: toString() with Array

In the above example, we have used the toString() method with an array. Here, we can see that the method can be called for the whole array or a single element of the array.

It is possible because Object class is the root of class hierarchy in Java. And, all the subclasses and arrays can use the method of the Object.

Note: We can also use the toString() method for the ArrayList class. To learn more, visit Java ArrayList toString().