SSJX.CO.UK
Content

Java StringBuilder

StringBuilder

In Java Strings can easily be joined using a '+'. For simple programs this is fine, but one of the problems with this method is that it is not quick. Joining strings in a loop as shown below can be very slow.

String txt="";
for(int i=0;i<100;i++){
	txt=txt+"abc";
}

Every time the 'txt' String changes, Java has to create a new String and mark the old one for removal later, this process takes time and eats up memory. Luckily Java has the faster and more efficient StringBuilder class which can be used instead!

StringBuilder Example

Joining strings with StringBuilder

The code below creates an empty StringBuilder, appends our text and then creates a string from it.

StringBuilder text = new StringBuilder();
text.append("Hello");
text.append("World");
System.out.println(text.toString());

Using StringBuilder in a loop

Below shows how you could use StringBuilder in a loop:

StringBuilder builder = new StringBuilder();
for(int i=0;i<100;i++){
	builder.append("abc");
}
String txt=builder.toString();

Benchmarking Java programs can very tricky due to many factors but the example below shows that StringBuilder is much faster than using the '+'.

Full Program

With the Java JDK installed, from a command line:

class JoinTest{
	public static void main(String[] args){	
		String txt="";
		
		// Timing strings being joined with a '+'
		long start = System.nanoTime();
		for(int i=0;i<100;i++){
			txt=txt+"abc";
		}
		long stop = System.nanoTime();
		System.out.println("Plus Time taken:\t"+(stop-start)+"ns");
		
		// Timing strings being joined with a StringBuilder
		start = System.nanoTime();
		StringBuilder builder = new StringBuilder();
		for(int i=0;i<100;i++){
			builder.append("abc");
		}
		txt=builder.toString();
		stop = System.nanoTime();
		
		System.out.println("SB Time taken:\t"+(stop-start)+"ns");
	}
}

Created
(07/05/2025)