Privacy Policy Terms Of Use. Copyright © 2006-2010 Java Tutorials and Examples.
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.
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.
This brings us end of Java StringBuffer Tutorial. Please let us know your views by leaving comment in the comments section.
<< StringBuffer Constructors

Post new comment