Difference Between String; StringBuffer and StringBuilder in Java?

String and StringBuffer, StringBuilder are the classes which operate on strings. Below are the differences:

Point of DistinctionStringStringBufferStringBuilder
LengthFixedIncreasedIncreased
Mutable Immutable. if you try to alter their values, another object gets createdMutable. It can change its valueMutable. you can add/remove characters, substring without creating new objects.
PerformanceSlowerFasterFaster
Memory ConsumptionMoreLessLess
StorageConstant PoolHeap Memory-
UseWhen String not going to changeString change and will be accessed from a multiple thread.String change and will only be accessed from a single thread.
Synchronized-YesNo
Thread Safe-Yes. multiple threads can call its method without compromising internal data structureNo
Efficient-Less than StringBuilderMore than StringBuffer

Example

package com.seleniumtest;

public class StringDifference 
{
	// Concatenates to String
	public static void concateString(String str1)
	{
		str1 = str1 + " World";
	}

	// Concatenates to StringBuffer
	public static void concateStringBuffer(StringBuffer str2)
	{
		str2.append(" World");
	}
	 
	// Concatenates to StringBuilder
	public static void concateStringBuilder(StringBuilder str3)
	{
		str3.append(" World");
	}

	public static void main(String[] args)
	{
		String str1 = "Hello";
		concateString(str1);  // str1 is not changed
		System.out.println("String: " + str1);

		StringBuffer str2 = new StringBuffer("Hello");
		concateStringBuffer(str2); // str2 is changed
		System.out.println("StringBuffer: " + str2);

		StringBuilder str3 = new StringBuilder("Hello");
		concateStringBuilder(str3); // str3 is changed
		System.out.println("StringBuilder: " + str3);	
	}
}

Output

String: Hello
StringBuffer: Hello World
StringBuilder: Hello World

Comments