Pages

Monday, January 5, 2015

String concatenation is the process of joining two or more small String to create a big String. For example you can create full name by concatenating first and last name of a person. Java provides multiple ways to concatenate String, but the easiest of them is by using + operator. It is one of the magical operator in Java, though Java doesn't support operator overloading, it has made an exception in case of String and + operator. Plus operator is a binary operator and primarily used to add two numbers if both operands are integer but it can also used to concatenate String if either both or first operand is String. For example "Java" + "Programming" will produce "JavaProgramming". You can use this operator even to convert integer to String in Java by concatenating an empty String with an integer. For example "" + 123 will produce String "123". Other two ways to concatenate String in Java is by using StringBuffer and StringBuilder. Both these classes are mutable counterpart of String class and used to modify mutable String. Since String is Immutable in Java, any operation on String, including concatenation always produce a new String object. If you use Plus operator to concatenate String in a loop, you will end up with lots of small String object which can fill up your heap and can create lot of work for your garbage collector. To avoid such issues, Java designers have provided StringBuffer and StringBuilder, both of which can be used to create mutable String which will not produce a new String object if you do concatenation. There is one more method to concatenate String in Java is by using String.concat() function. You can use this one for String concatenation.

4 Ways to concatenate String in Java

As explained in first paragraph, there are three main ways to concatenate String in Java :

Concatenation operator (+)

StringBuffer class

StringBuilder class

String.concat() function

Let's see examples of each way to concatenate two String object in Java.

String concatenation using + Operator

This is the most simple way to do the job. For example "One" + "Two" will produce a String object "OneTwo". You can use this operator to combine more than one String e.g. two, three, four or any number of String object like "abc" + "def" + "ghi" + "jklm" will result in "abcdefghijklm". You can also use String literal or String variable, it will work in both scenario. Most important thing to remember about doing String concatenation is that it doesn't modify any String object and always create a new String object. If you use literal or if the object is already exists in pool, then it may return object from String pool but otherwise it will result in a new String object. Never use this method while concatenating String in loop, it will result in lots of small String garbage. Also don't forget to store the reference of object returned by + operator. You can also use this method to convert int to String in Java, provided they are always the second operand.

Concatenate String using StringBuffer and StringBuilder class

This is right way to join multiple String in Java. Why? because it represent a mutable String and when you concatenate multiple small String, it won't generate temporary intermediate String object. This result in lot of memory saving and reduce garbage collection time. By the way, you should always use StringBuilder instead of StringBuffer because it provides the same functionality but without any synchronization overhead, which means faster operation. Use of StringBuffer or StringBuilder also results in fluent and readable code as shown below :

You can see that how easy is to join multiple String using StringBuilder. By the way don't forget to initialize StringBuilder with required capacity which is equal to number of characters in final String. This will save memory by utilizing object properly and reduce CPU time spent during re-sizing of StringBuilder.

Java Program to Concatenate String in Java

Here is our sample Java program which will show you how you can use these three ways to concatenate String in Java. In first example, we have used + operator, while in second and third example we have used StringBuilder and StringBuffer class to join Strings in Java.

Performance of String concatenation in Java

As I told you the quickest way of concatenating String in Java is by using concatenation operator ("+") and it works quite well if you just have to join one or two fixed size String, but if you have to join thousands of String or you are performing String concatenation in loop then performance of concatenation operator is not good. Main reason of performance drop is creation of lots of temporary String object due to immutability of String. If you are doing lot of String concatenation in your Java application and concern how different ways will perform, I would suggest you to read this article, which compares performance of concatenation operator, String.concat() function, StringBuilder and StringBuffer using Perf4j. You can see with results that it confirms the theory that for large scale of String concatenation StringBuilder is the best approach. For your information, following String concatenation performance benchmark is from 64-bit OS (Windows 7), 32-bit JVM (7-ea), Core 2 Quad CPU (2.00 GHz) with 4 GB RAM, so it's quite relevant.

That's all about how to concatenate String in Java. We have leaned how we can use Plus operator +, StringBuffer and StringBuilder to join multiple String literal or object to produce a new bigger String. Just remember that String concatenation using + operator is also converted to corresponding StringBuffer and StringBuilder call depending upon which version of Java you are using because StringBuilder is only available from Java 1.5. Few key things you should remember :

Don't use + operator for String concatenation in loop.

Always use StringBuilder for concatenation of multiple String.

Always initialize StringBuilder with proper capacity.

Thanks a lot for reading this far, if you like this article then don't forget to check other String related posts as well like :

Why character array is better than String for storing password? (read here)

The reason for the slowness when appending many strings in a loop using the + operator is that the + operator creates and disposes of a new StringBuffer for every + operator. So not only are you creating many small String objects, but each one of them was created by a temp StringBuffer object. Both the temp String and the temp StringBuffer then get garbage collected.

@Han.Solo..perfect dude..If you want to join a Collection of Strings you can use the new String.join() method:

List list = Arrays.asList("foo", "bar", "baz");String joined = String.join(" and ", list); // "foo and bar and baz"If you have a Collection with another type than String you can use the Stream API with the joining Collector:

I have recently came across a problem in load testing. String is concatenated using + operator.Concatenated String corrupts only while using VM parameters -XX:+UseCompressedStrings -XX:+OptimizeStringConcat. Can somebody throw some light on it.. I will share my results if I find before someone explains it..