toString() Method in Java

Last Updated : 17 Dec, 2025

The toString() method is defined in the java.lang.Object class and returns a string representation of an object. It is commonly overridden to provide meaningful, human-readable details about an object's state and is automatically invoked when an object is printed or concatenated with a string.

Converting String object to String

In this example, we are creating a string object and then converting it to string datatype using toString() method.

java
import java.io.*;
public class Geeks {

    public static void main(String args[])
    {
        String Strobj = new String("Welcome to the world of geeks.");
        System.out.print("Output String Value: " + Strobj.toString());
    }
}

Output
Output String Value: Welcome to the world of geeks.

Explanation:

  • new String("Welcome to the world of geeks."): creates a String object referenced by Strobj.
  • Strobj.toString(): returns the same string content stored in the object.

Syntax:

public String toString()

  • Parameter: This method does not accept any parameters.
  • Return Type: String.

Below are some of the examples of toString method:

Printing a String Using toString()

In this example, the "toString()" method is explicitly called while printing a String object to the console.

java
public class Geeks {
    public static void main(String[] args) {
        String Strobj = "Thank You";
        System.out.println("Output : " + Strobj.toString());
    }
}

Output
Output : Thank You

Explanation

  • String Strobj = "Thank You": creates a string literal and assigns it to Strobj.
  • Strobj.toString(): returns the same string value because String overrides toString().
  • System.out.println(): prints the returned string along with the prefix text.
Comment