Java Object toString()

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

Example

class Main {
  public static void main(String[] args) {

    // toString() with Object
    Object obj1 = new Object();
System.out.println(obj1.toString());
} } // Output: java.lang.Object@7a81197d

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

class Main {
  public static void main(String[] args) {

    // toString() with Object
    Object obj1 = new Object();
System.out.println(obj1.toString()); // java.lang.Object@6a6824be
Object obj2 = new Object(); System.out.println(obj2.toString()); // java.lang.Object@5c8da962 Object obj3 = new Object(); System.out.println(obj3.toString()); // java.lang.Object@512ddf17 } }

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

class Main {
  public static void main(String[] args) {

    // toString() with array
    // create an array
    String[] array = {"Python", "Java", "C"};
System.out.println(array.toString()); // [Ljava.lang.String;@6a6824be
// toString() with each element of array
System.out.println(array[0].toString()); // Python
} }

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().

Did you find this article helpful?