Skip to content

StringBuffer and StringBuilder

Estimated time to read: 1 minute

Overview

Although it is handy to have a simple way to create String objects, overuse of them can slow performance of the system.

To help reduce performance problems, Java includes the StringBuilder class. StringBuilder is used to manipulate string data.

StringBuffer is deprecated and it is now recommended to use StringBuilder. StringBuffer was a synchronous process that would hang a thread whilst work was undertaken.

Dynamic Strings with StringBuilder

StringBuilder provides dynamic string manipulation without the performance overhead of the String class.

StringBuilder nameBuffer = new StringBuilder("John");

nameBuffer.append(" ");
nameBuffer.append("Richard");
nameBuffer.append(" ");

nameBuffer.append(" ");
nameBuffer.append("Cornwell");

System.out.println(nameBuffer.toString()); // StringBuilders must be converted to Strings before they can be printed

The StringBuilder automatically manages its size and will scale accordingly. The optimised buffer size is only generated once the StringBuilder is converted to a String.