Java StringBuilder

Java StringBuilder is identical to StringBuffer except for one important difference it is not synchronized , that means it is not thread safe. The main difference between StringBuffer and StringBuilder is StringBuffer is synchronized, but StringBuilder is not. You should prefer StringBuilder in all cases where you have only a single thread accessing your object. The important methods in StringBuilder Class are append() , insert() , replace() , delete() , reverse() , and capacity() . The following Java program illustrate the important methods in StringBuilder Class. Example
class TestClass{ public static void main (String[] args){ //adding values in StringBuilder StringBuilder sb = new StringBuilder("The "); sb.append( "Java " ); sb.append( "Tutorial " ); System.out.println(sb); //output: The Java Tutorial //insert the specified string with this string at the specified position sb.insert(8," StringBuilder "); System.out.println(sb); //output: The Java StringBuilder Tutorial //replace the string from specified startIndex and endIndex sb.replace(4,4,"Good"); System.out.println(sb); //output: The GoodJava StringBuilder Tutorial //delete the string from specified startIndex and endIndex sb.delete(0,4); System.out.println(sb); //output: GoodJava StringBuilder Tutorial //reverse the string sb.reverse(); System.out.println(sb); //output: lairotuT redliuBgnirtS avaJdooG //return the current capacity StringBuilder nsb = new StringBuilder(); System.out.println(nsb.capacity()); //output: 16 , the default capacity 16 nsb.append("The Java Tutorial "); System.out.println(nsb.capacity()); //output: 34 , (oldcapacity*2)+2 , (16*2)+2 } }
Output
The Java Tutorial The Java StringBuilder Tutorial The GoodJava StringBuilder Tutorial GoodJava StringBuilder Tutorial lairotuT redliuBgnirtS avaJdooG 16 34 34 34

StringBuilder append() method

The principal operations on a StringBuilder are the append method, which are overloaded so as to accept data of any type. String appends become increasingly expensive as strings become longer and more memory is required. For example:
class TestClass{ public static void main (String[] args) { String str = ""; for (int i = 0; i < 100; i++) { str += ", " + i; } System.out.println(str); } }
In the above case, you should use a StringBuilder instead of a String, because it is much faster and consumes less memory.
class TestClass{ public static void main (String[] args) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100; i++) { sb.append(i + ", " ); } System.out.println(sb); } }

If you have a single statement,

String s = "a, " + "b, " + "c, " + "d, " ...;

then you can use Strings, because the compiler will use StringBuilder automatically.

Mutability Difference of String and StringBuilder

String is immutable , if you try to alter their values, another object gets created, whereas StringBuilder are mutable so they can change their values.