Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Aug 27, 2001



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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";

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();

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.
Ramneek Handa
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date