Home Java SCJP SCWCD Servlet Submit News Contact Us Site Map


Over 500 magazines for free (including Oracle Magazine)!

Yes all of them are FREE. You can subscribe to ALL of them.
Click here to apply today!

String concatenation and StringBuffer

In Java, String concatenation operator (+) is internally implemented using StringBuffer.

For Example,

String str = “Hello” + “World”;

Would be executed as,

String str = new StringBuffer().append(“Hello”).append(“World”).toString();

First an empty StringBuffer will be created and then operands of the + operator would be appended using append method of the StringBuffer.

Finally toString() method of the StringBuffer would be called to convert it to string object and the same will be returned.

String concatenation using this approach is very expensive in nature, because it involves creation of temporary StringBuffer object. Then that temporary object’s append method gets called and the resulting StringBuffer should be converted to back String representation using toString() method.

When to use String and when StringBuffer?

If there is a need to change the contents frequently, StringBuffer should be used instead of String because StringBuffer concatenation is significantly faster than String concatenation.


<< StringBuffer Constructors

Home Java SCJP SCWCD Servlet Site map