3 Examples to Concatenate String in Java

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 :


  1. Concatenation operator (+)
  2. StringBuffer class
  3. StringBuilder class
  4. 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 :

String result = new StringBuilder(14).append(firstname).append(" ").append(lastname).toString();

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.

/**
 * Java program to show how to concatenate String in Java.
 * Easiest way is by using + operator, "abc" + "def" will
 * produce a new concatenated String "abcdef"
 * 
 * @author WINDOWS 8
 */

public class StringConcat{

    public static void main(String args[]) {
        
        String firstname = "Virat";
        String lastname = "Kohli";
        
        // 1st way - Use + operator to concatenate String      
        String name = firstname + " " + lastname;
        System.out.println(name);
        
        
        // 2nd way - by using StringBuilder
        StringBuilder sb = new StringBuilder(14);
        sb.append(firstname).append(" ").append(lastname);
        System.out.println(sb.toString());
        
        
        // 3rd way - by using StringBuffer
        StringBuffer sBuffer = new StringBuffer(15);
        sBuffer.append(firstname).append(" ").append(lastname);
        System.out.println(sBuffer.toString());
       
    }     
   
}

Output
Virat Kohli
Virat Kohli
Virat Kohli



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.

4 Examples of String concatenation in Java


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 :

  1. Why character array is better than String for storing password? (read here)
  2. Best way to check if String is empty in Java? (see here)
  3. Why String is final in Java? (read here)
  4. Difference between StringBuffer and StringBuilder in Java? (read here)
  5. Why use equals() to compare String in Java? (check here)


12 comments :

Christian Ullenboom said...

One could add that StringJoiner (Java 8) and String.format(...)/Formatter are two other ways of "joining" (concatenating) Strings.

SARAL SAXENA said...

Lots of theory - time for some practice!

private final String s1 = new String("1234567890");
private final String s2 = new String("1234567890");

Using plain for loops of 10,000,000, on a warmed-up 64-bit Hotspot, 1.6.0_22 on Intel Mac OS.

eg

@Test public void testConcatenation() {
for (int i = 0; i < COUNT; i++) {
String s3 = s1 + s2;
}
}

With the following statements in the loops

String s3 = s1 + s2;

1.33s

String s3 = new StringBuilder(s1).append(s2).toString();

1.28s

String s3 = new StringBuffer(s1).append(s2).toString();

1.92s

String s3 = s1.concat(s2);

0.70s

String s3 = "1234567890" + "1234567890";

0.0s

So concat is the clear winner, unless you have static strings, in which case the compiler will have taken care of you already.

Rick Ryker said...

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.

Javin Paul said...

@Saral, In your test I you are always adding same string together. Can you try using loop counter to append and see what it returns? I think StringBuilder should win the race.

yottzumm said...

@Javin, the point is, people are often adding static strings to avoid long lines. The compiler takes care of it, so don't worry and create a bunch of ugliness in your code.

Han.Solo said...

There is also StringJoiner and String.join() which came with JDK8...

SARAL SAXENA said...

@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:

List list = Arrays.asList(
new Person("John", "Smith"),
new Person("Anna", "Martinez"),
new Person("Paul", "Watson ")
);

String joinedFirstNames = list.stream()
.map(Person::getFirstName)
.collect(Collectors.joining(", ")); // "John, Anna, Paul"
The StringJoiner class may also be useful.

Nataraj Boya said...

Nice article.. Thanks it helped

Unknown said...

Given two strings first and second, appends onto first all characters in second that
don't already occur in first

Help

Jane Rose said...

Thanks

Javin Paul said...

@Jane, glad that you like this tutorial about different ways of concatenating Strings. If you like, don't forget to share, it makes difference. Thanks

PRITAM KUMAR said...

good job

Post a Comment