Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Beginner
Jan 5, 2002



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

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)

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