devxlogo

Use Stringbuffer When Appending to Strings

Use Stringbuffer When Appending to Strings

In Java, Strings are immutable objects. This means that they cannot be modified in any way after they are created. When you attempt to modify a String object, you often end up doing much more work than you expected, or need to.
For example, here is a simple and common method of concatenating values together in Java:

 String aString = "";aString = aString+"a";aString = aString+"b";System.out.println(aString);

size=3>
Because Strings are immutable, the old aString object has to be discarded and a new aString object created every time a new string is appended. In terms of both execution time and memory consumption, object creation can be one of the most costly types of operations in Java.
Compare that to the StringBuffer approach:

 StringBuffer aBuffer = new StringBuffer();aBuffer.append("a");aBuffer.append("b");System.out.println(aBuffer.toString());

size=3>
By using a StringBuffer object, the appended strings are added directly to the internal byte array of the StringBuffer rather than causing a new String object to be allocated.
In general, if you find yourself appending values to a String more than once in the lifetime of the String object, using a StringBuffer to manage your changing values can improve the speed and efficiency of your Java code.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist