When we think about String Concatenation in Java, what comes in our mind is + operator, one of the easiest way to join two String, or a String and a numeric in Java. Since Java doesn't support operator overloading, it's pretty special for String to have behavior. But in truth, it is the worst way of concatenating String in Java. When you concatenate two String using + operator e.g. "" + 101, one of the popular way to convert int to String, compiler internally translate that to StringBuilder append call, which result in allocation of temporary objects. You can see the real difference in performance of our example program, in which we have concatenated 100,000 String using + operator. Anyway, this article is not just about + operator but also about other ways to concatenate multiple Strings. There are four ways to do this, apart from + operator, we can use
StringBuffer,
StringBuilder and
concat() method from
java.lang.String class for same purpose. StringBuilder and StringBuffer classes are there for just this reason, and you can see that in our performance comparison. StringBuilder is winner and fastest ways to concatenate Strings. StringBuffer is close second, because of synchronized method and rest of them are just 1000 times slower than them. Here we will see example of all four ways of concatenating Strings in Java.