Difference between String and StringBuilder

String is immutable, and cannot be changed in its current location itself. For example, when tried to append a String to another, a new String gets created combining old String with new one.

StringBuffer is mutable and can gets changed in its location itself.

Below is example program showing difference between String and StringBuffer.

public class StringAndBufferDemo {
public static void main(String args[])
	{
		String str = new String("first");
		//String is immutable i..e once created cannot be changed

		str = str.concat("ggggg");
		//str doesn't get updated itself, rather concatenated string is returned
		//old str object with "first" value remains unchanged and continues to exist,
		//even after new concatinated string "first ggggg" gets created

		System.out.println(str);

		str.replaceAll("f", "k");
		System.out.println(str);

		StringBuffer strb = new StringBuffer("second");
		//StringBuffer is mutable, and can grows and shrink in size dynamically

		strb.reverse();

		System.out.println(strb);

		strb.append(" tttttt");

		System.out.println(strb);

		strb.insert(6, "bbbbbbbbb");

		System.out.println(strb);

		strb.delete(3, 7);

		System.out.println(strb);
	}

}


Output:
firstggggg
firstggggg
dnoces
dnoces tttttt
dnocesbbbbbbbbb tttttt
dnobbbbbbbb tttttt

One thought on “Difference between String and StringBuilder”

Leave a Reply