Tutorials and What's HOT 

Is String concatenation still a taboo?

by budi kurniawan

Posted on Monday Sep 01, 2014 at 10:23PM in Java

Every good Java programmer knows that String objects are immutable and a String concatenation always creates a new String and is therefore an expensive operation that should be avoided. In other words, code like this is a taboo:

String s = "Hello";
s += ", World";
Or, is it?

For years, we've been advised to use StringBuilder instead, but today's Java compilers are more intelligent than ever. The Oracle Java compiler (and probably others) will convert the code above to something like this:

StringBuilder builder = new StringBuilder("Hello");
builder.append(", World");
String s = builder.toString();

How do you prove this? If you have Eclipse installed on your computer, simply create a test class and double-click the .class file in the Navigator view. The disassembled bytecode would look like this:

     0  ldc  [16]
     2  astore_1 [s1]
     3  new java.lang.StringBuilder [18]
     6  dup
     7  aload_1 [s1]
     8  invokestatic java.lang.String.valueOf(java.lang.Object) : java.lang.String [20]
    11  invokespecial java.lang.StringBuilder(java.lang.String) [26]
    14  ldc  [29]
    16  invokevirtual java.lang.StringBuilder.append(java.lang.String) : java.lang.StringBuilder [31]
    19  invokevirtual java.lang.StringBuilder.toString() : java.lang.String [35]
    22  astore_1 [s1]

See how in Line 3 the bytecode creates a StringBuilder?

So, should you start concatenating Strings because it's shorter than using StringBuilder? It depends. If every member in your team knows that compilers are smart, then yes. If not, your manager might think you don't even know the basic rule of working with Strings. Who says this will not cause a delay of your promotion?


I was extremely inspired with this blog. It is so far the best I have gone by amid my distributions on the article site.

Posted by Write My Essay on December 27, 2017 at 06:14 AM UTC #

The leading assignment help UK firm offers state of the art services to its clients with a promise of delivering all the required work well within the deadline.

Posted by Matlab Programming Project Help on January 13, 2018 at 05:28 AM UTC #

Things are very open and intensely clear explanation of issues. was truly information. Your website is very beneficial.

Posted by dissertation helpers on January 15, 2018 at 04:35 AM UTC #

Leave a Comment

HTML Syntax: NOT allowed