Entries tagged [concatenation]
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:
 2 astore_1 [s1] 3 new java.lang.StringBuilder  6 dup 7 aload_1 [s1] 8 invokestatic java.lang.String.valueOf(java.lang.Object) : java.lang.String  11 invokespecial java.lang.StringBuilder(java.lang.String)  14 ldc  16 invokevirtual java.lang.StringBuilder.append(java.lang.String) : java.lang.StringBuilder  19 invokevirtual java.lang.StringBuilder.toString() : java.lang.String  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?