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

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: