String concatenation in Java – when to use +, StringBuilder and concat [duplicate]

Modern Java compiler convert your + operations by StringBuilder’s append. I mean to say if you do str = str1 + str2 + str3 then the compiler will generate the following code:

StringBuilder sb = new StringBuilder();
str = sb.append(str1).append(str2).append(str3).toString();

You can decompile code using DJ or Cavaj to confirm this 🙂
So now its more a matter of choice than performance benefit to use + or StringBuilder 🙂

However given the situation that compiler does not do it for your (if you are using any private Java SDK to do it then it may happen), then surely StringBuilder is the way to go as you end up avoiding lots of unnecessary String objects.

Leave a Comment