StringBuilder toString() method in Java with Examples (original) (raw)

Last Updated : 23 Jan, 2023

The toString() method of the StringBuilder class is the inbuilt method used to return a string representing the data contained by StringBuilder Object. A new String object is created and initialized to get the character sequence from this StringBuilder object and then String is returned by toString(). Subsequent changes to this sequence contained by Object do not affect the contents of the String.

Syntax:

public abstract String toString() ;

Return Value: This method always returns a string representing the data contained by StringBuilder Object.

As this is a very basic method been incorporated in java so we will be discussing it within our clean java programs to get to know its working. INternally in the class, it is defined as follows which will give you a better understanding of how it actually works.

return getClass().getName()+ "@" + Integer.toHexString(hashCode);

Example 1:

Java

import java.io.*;

class GFG {

`` public static void main(String[] args)

`` {

`` StringBuilder str

`` = new StringBuilder( "GeeksForGeeks" );

`` System.out.println( "String contains = "

`` + str.toString());

`` }

}

Output

String contains = GeeksForGeeks

Example 2:

Java

import java.io.*;

class GFG {

`` public static void main(String[] args)

`` {

`` StringBuilder str = new StringBuilder(

`` "Geeks for Geeks contribute" );

`` System.out.println( "String contains = "

`` + str.toString());

`` }

}

Output

String contains = Geeks for Geeks contribute

Now we are done with discussing basic examples let us operate the same over an array of strings by converting it to a single string using to.String() method. Here we will create a StringBuilder class object then we will store the array of string as its object. Later on, we will create another string and will throw all elements in this. Lastly, we will print this string.

Example 3:

Java

import java.io.*;

import java.util.*;

class GFG {

`` public static void main(String[] args)

`` {

`` String gfg[] = { "Are" , "You" , "A" , "Programmer" };

`` StringBuilder obj = new StringBuilder();

`` obj.append(gfg[ 0 ]);

`` obj.append( " " + gfg[ 1 ]);

`` obj.append( " " + gfg[ 2 ]);

`` obj.append( " " + gfg[ 3 ]);

`` String str = obj.toString();

`` System.out.println(

`` "Single string generated using toString() method is --> "

`` + str);

`` }

}

Output

Single string generated using toString() method is --> Are You A Programmer

Similar Reads

Java Basic Programs





















Java Pattern Programs














Java Conversion Programs















Java Classes and Object Programs
















Java Methods Programs











Java Searching Programs




Java 1-D Array Programs













Java 2-D Arrays (Matrix) Programs













Java String Programs