Skip to main content Skip to docs navigation
TechSpiderTutorials

StringBuilder Class in Java

On this page

Java StringBuilder Definition

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 string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

Java StringBuilder Example

import java.lang.*;

public class StringBuilderDemo 
{
 public static void main(String[] args) 
 {
	 StringBuilder stb=new StringBuilder("welcome to Oracle software");
	 System.out.println("Original String is..."+stb);
	 System.out.println("capacity is..."+stb.capacity());
	 System.out.println("size...."+stb.length());
	 
	 System.out.println("Appended String is..."+stb.append(" India"));
	 System.out.println("capacity is..."+stb.capacity());
	 System.out.println("size...."+stb.length());
	 
	 System.out.println("inserted String is..."+stb.insert(26, " & Hardware"));
	 System.out.println("String after delete is..."+stb.delete(0, 8));
	 System.out.println("Replaced String is..."+stb.replace(30, 35, "USA"));
	 System.out.println("string reverse is..."+stb.reverse());
	 
	 System.out.println("capacity is..."+stb.capacity());
	 System.out.println("size...."+stb.length());
	 			stb.trimToSize();
	System.out.println("capacity is..."+stb.capacity());
	 System.out.println("size...."+stb.length());
	 
	} 
}

Output:

Original String is...welcome to Oracle software
capacity is...42
size....26
Appended String is...welcome to Oracle software India
capacity is...42
size....32
inserted String is...welcome to Oracle software & Hardware India
String after delete is...to Oracle software & Hardware India
Replaced String is...to Oracle software & Hardware USA
string reverse is...ASU erawdraH & erawtfos elcarO ot
capacity is...86
size....33
capacity is...33
size....33