java.lang.StringBuilder Class

A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the StringBuffer was being used by a single thread. It is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.

In this tutorial you can learn how to create StringBuilder and how to use StringBuilder.

java.lang.StringBuilder Class Example
/* StringBuilder Example with Default Constructor */
/* Save with file name StringBuilderExample1.java */

public class StringBuilderExample1
{
	public static void main(String args[])
	{
		//DECLARATION
		StringBuilder s1;
		//CREATE INSTANCE USING DEFAULT CONSTRUCTOR
		//THE VALUE OF STRINGBUILDER IS EMPTY
		s1 = new StringBuilder();
		//OUTPUT EMPTYSTRING
		System.out.println("StringBuilder value : " + s1);
	}
}
                        
java.lang.StringBuilder Class Example 2
/* StringBuilder Example with Parameter Constructor */
/* Save with file name StringBuilderExample2.java */

public class StringBuilderExample2
{
	public static void main(String args[])
	{
		//DECLARATION
		StringBuilder s1;
		//CREATE INSTANCE USING PARAMETER CONSTRUCTOR
		s1 = new StringBuilder("Huda Tutorials");
		//OUTPUT
		System.out.println("StringBuilder value : " + s1);
	}
}
                        

In the following example you can learn how to reverse string using StringBuilder.

java.lang.StringBuilder Class Example 3
/* Save with file name StringBuilderExample3.java */

public class StringBuilderExample3
{
	public static void main(String args[])
	{
		//DECLARATION
		StringBuilder s1;
		//CREATE INSTANCE USING PARAMETER CONSTRUCTOR
		s1 = new StringBuilder("abcd");
		//REVERSE STRING USING REVERSE METHOD
		System.out.println("Reverse String is : " + s1.reverse());
	}
}
                        

In the following example you can learn how to append String into StringBuilder.

java.lang.StringBuilder Class Example 4
/* Save with file name StringBuilderExample4.java */

public class StringBuilderExample4
{
	public static void main(String args[])
	{
		//DECLARATION
		StringBuilder s1;
		//CREATE INSTANCE USING PARAMETER CONSTRUCTOR
		s1 = new StringBuilder("Huda");
		s1.append("Tutorials");
		//APPENDED STRING
		System.out.println("String is : " + s1.toString());
	}
}