Java Utility Library

Java Object - toString() Method



The java.util.Object.toString() method returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

Syntax

public String toString()

Parameters

No parameter is required.

Return Value

Returns a string representation of the object.

Exception

NA

Example:

In the example below, the java.util.Object.toString() method returns a string representation of the given object.

import java.lang.*;
import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating an ArrayList object
    ArrayList<Integer> MyList = new ArrayList<Integer>();

    //populating ArrayList
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);

    //printing ArrayList
    System.out.println("MyList contains: " + MyList);

    //creating and printing the string 
    //representation of the object
    String MyStr = MyList.toString();
    System.out.println("The string representation is: " + MyStr);
  }
}

The output of the above code will be:

MyList contains: [10, 20, 30]
The string representation is: [10, 20, 30]

❮ Java.lang - Object