Java String toString Method

The Java String toString Method is one of the String Methods, which is to return the string representation of the user-specified Object (String is also an Object). In this article, we will show how to use this String.toString method with an example. The syntax of the String toString is as shown below.

The Java Programming Language provides to String method to return the string of itself. The following Java String toString method will not accept any parameters and convert the Object into a string.

public String toString(); // It will return String 

//In order to use in program
Object.toString()

Java String toString Method Example

The String toString method returns the string representation of the user-specified object. This program will help to understand the string.toString method.

package StringFunctions;

public class ToStringMethod {
 public static void main(String[] args) {
 String str = "Learn Java Programming at Tutorial GateWay";
 
 String str1 = str.toString();
 String str2 = "Java Programming Language".toString();
 String str3 = "Tutorial Gateway".toString();
 String str4 = new String("Read This Programming Sentence");
 
 System.out.println( "toString Method Result = " + str1);
 System.out.println( "toString Method Result = " + str2);
 System.out.println( "toString Method Result = " + str3);
 System.out.println( "toString Method Result = " + str4.toString());
 }
}
Java String toString 1

In this Java to String method, first, we declared the String variable and assigned a value using the following statement.

String str = "Learn Java Programming at Tutorial GateWay";

The following statements will convert the Object into String.

String str4 = new String("Read This Programming Sentence");

The following Java System.out.println statements will print the output. Within the last statement, we used the toString String Method on string object str4. From the above screenshot, see that it is returning the string representation of the sentence.

System.out.println( "toString Method Result = " + str1);
System.out.println( "toString Method Result = " + str2);
System.out.println( "toString Method Result = " + str3);
System.out.println( "toString Method Result = " + str4.toString());