See the Tutorial List

StringBuilder class in Java

StringBuilder is identical to StringBuffer except for one important difference that it is not synchronized, which means it is not thread safe. Its because StringBuilder methods are not synchronised.


StringBuilder Constructors

  1. StringBuilder ( ), creates an empty StringBuilder and reserves room for 16 characters.
  2. StringBuilder ( int size ), create an empty string and takes an integer argument to set capacity of the buffer.
  3. StringBuilder ( String str ), create a StringBuilder object and initialize it with string str.

Difference between StringBuffer and StringBuilder class

StringBuffer classStringBuilder class
StringBuffer is synchronized.StringBuilder is not synchronized.
Because of synchronisation, StringBuffer operation is slower than StringBuilder.StringBuilder operates faster.
StringBuffer is thread-safeStringBuilder is not thread-safe
StringBuffer is less efficient as compare to StringBuilderStringBuilder is more efficient as compared to StringBuffer.
Its storage area is in the heapIts storage area is the stack
It is mutableIt is mutable
Methods are synchronizedMethods are not synchronized
It is alternative of string classIt is more flexible as compared to the string class
Introduced in Java 1.0Introduced in Java 1.5
Its performance is moderateIts performance is very high
It consumes more memoryIt consumes less memory

Example:

	
public class BufferDemo{
    public static void main(String[] args){  
StringBufferobj=new StringBuffer("Welcome to ");  
obj.append("studytonight.com");  
System.out.println(obj);  
    }  
}  
	

Welcome to studytonight.com

Example:

		
public class BuilderDemo{
    public static void main(String[] args){  
StringBuilderobj=new StringBuilder("Welcome to ");  
obj.append("studytonight.com");  
System.out.println(obj);  
    }  
}  	
	

Welcome to studytonight.com


Example of StringBuilder

class Test {
 public static void main(String args[])
 {
  StringBuilder str = new StringBuilder("study");
  str.append( "tonight" );
  System.out.println(str);
  str.replace( 6, 13, "today");
  System.out.println(str);
  str.reverse();
  System.out.println(str);
  str.replace( 6, 13, "today");
 }
}

studytonight studyttoday yadottyduts