devxlogo

Use StringBuffer Instead of Strings for Object Concatenation

Use StringBuffer Instead of Strings for Object Concatenation

Most of us have the tendency to write:

 String s1 = "Hello";String s2 = "World";String s3 = s1 + s2;

However, the above is an expensive operation. As Strings are immutable, the code creates a new String object every time you try to alter the contents of the String.

Java has provided a variant of the String class- StringBuffer, which is mutable. StringBuffer can be used simply as:

 StringBuffer sbuf (assume it is created)sbuf.append(s1);

And so on, if you are constructing a big string. Later this can be converted into a String object by the method (fatherof them all) toString().

See also  Why ChatGPT Is So Important Today
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