Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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

 

 

 

 

 


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

 

 

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