String concatenation is the process of joining two or more small String to create a big String. For example, you can create a 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 operators in Java, though Java doesn't support operator overloading, it has made an exception in the case of String and + operators. 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 an integer to String in Java by concatenating an empty String with an integer. For example "" + 123 will produce String "123".
The other two ways to concatenate String in Java is by using StringBuffer and StringBuilder. Both these classes are the mutable counterpart of String class and used to modify mutable String. Since String is Immutable in Java, any operation on String, including concatenation always produces 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 a 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.
Before going for a programming/coding interview, It's absolutely necessary to do as much practice in data structure and algorithms as possible to take advantage of all the knowledge available. You can also join these online Data structures and Algorithms courses to fill the gaps in your understanding.
Let's see examples of each way to concatenate two String object in Java.
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.
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.
That's all about how to concatenate String in Java. We have learned 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 :
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 :
You can use this operator even to convert an integer to String in Java by concatenating an empty String with an integer. For example "" + 123 will produce String "123".
The other two ways to concatenate String in Java is by using StringBuffer and StringBuilder. Both these classes are the mutable counterpart of String class and used to modify mutable String. Since String is Immutable in Java, any operation on String, including concatenation always produces 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 a 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.
Before going for a programming/coding interview, It's absolutely necessary to do as much practice in data structure and algorithms as possible to take advantage of all the knowledge available. You can also join these online Data structures and Algorithms courses to fill the gaps in your understanding.
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.
1. 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.
2. 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.
The main reason for performance drop is the creation of lots of temporary String object due to the immutability of String. If you are doing a 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 the 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.
The main reason for performance drop is the creation of lots of temporary String object due to the immutability of String. If you are doing a 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 the 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.
- 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)
- Best way to check if String is empty in Java? (see here)
- Why String is final in Java? (read here)
- Difference between StringBuffer and StringBuilder in Java? (read here)
- Why use equals() to compare String in Java? (check here)
15 comments :
One could add that StringJoiner (Java 8) and String.format(...)/Formatter are two other ways of "joining" (concatenating) Strings.
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.
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.
@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.
@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.
There is also StringJoiner and String.join() which came with JDK8...
@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.
Nice article.. Thanks it helped
Given two strings first and second, appends onto first all characters in second that
don't already occur in first
Help
Thanks
@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
good job
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..
read three input string, concatenate and print using JSP and servlet with Jsp script tag and expression tag
how can you validate the name if it contains both firstName and lastName
Post a Comment