Concatenation of strings in Java
String concatenation is the operation of merging two or more small Strings to create a final String. For example, you can create the full name by concatenating the person's first and last name. Java provides several ways to concatenate strings, but the easiest of them is to use the + operator. There are four ways to concatenate strings in Java:- The concatenation operator '+'
- The function String.concat()
- The StringBuilder
- The StringBuffer
Concatenate strings with the operator +
You can use the operator '+' to concatenate two or more strings, this is the easiest way to get the job done. For example, "One" + "Two" will produce the String object "OneTwo". You can use this operator to combine at least two Strings, for example: "ab"+"cde"+fghi" will give "abcdefghi", and you can also use String variables.
This operation is transformed by the compiler into:
This operation is transformed by the compiler into:
new StringBuilder().append("string1").append("string2").toString()This program concatenates two strings:
public class Concatenation_string {Runtime:
public static void main(String[] args) {
String s1 = "string1";
String s2 = "string2";
String s1s2 = concatenation_strings_java(s1, s2);
System.out.println(s1s2);
}
public static String concatenation_strings_java (String s1, String s2) {
return s1+s2;
}
}
string1chain2
Concatenate strings with the String.concat()
This method concatenates one String at the end of another. The method returns a String with the value of String passed in the concatenated method with the end of the String used to invoke that method.public String concat(String s)Example:
public class Concatenation_string {Runtime:
public static void main(String[] args) {< br /> String s = "I am one";
s = s.concat(" programmer");
System.out.println(s);
}
}
I'm a programmer
Difference between the '+' operator and the String.concat()
To be able to distinguish the difference between the '+' and the concat(), we'll work with a practical example.a+=bFirst, there's a small difference in the semantics. If a is null, then a.concat(b) triggers a NullPointerException, but the '+' in the statement a+=b processes the value of a even if it is null. In addition, the concat() accepts only String values while the '+' operator converts the value to a String( using the toString() ). We can say that the method concat() is stricter in that it accepts.
a.concat(b)
You can write this code and see what you get in output:
public static void main(String[] args) {You should have this at runtime:
String s = null;
s = s.concat(" programmer");
System.out.println(s);
}
Exception in thread "main" java.lang.NullPointerExceptionThe same example with the '+':
at Concatenation_string.main(Concatenation_string.java:5)
public static void main(String[] args) {You should have this result:
String s = null;
s = s + programmer;
System.out.println(s);
}
nullprogrammerSo, as we said earlier, the operator '+' is equivalent to:
a = new StringBuilder()
.append(a)
.append(b)
.toString();
Concatenate strings with StringBuffer and StringBuilder
This means of concatenation reduces memory and time costs because it will not generate String objects. In fact, you should always use StringBuilder instead of StringBuffer because it has the same functionality but without synchronization, which means a faster operation. Using StringBuffer or StringBuilder also results in structured code as shown below:String result = new StringBuilder(15).append(name).append(" ").append(firstname).toString();You can see how easy it is to concatenate multiple Strings using StringBuilder. However, remember to initialize StringBuilder with a capacity equal to the number of characters in the final string. This will prevent losing unusable memory by properly initializing our String and reduce CPU time.
Here is an example of a java program that will show you how to concatenate a String with StringBuilder and StringBuffer.
public static void main(String[] args) {Output:
String court ="Court of";
String module_math ="math";
/* StringBuilder */
String module_res = "networks";
int length = court.length()+module_math.length();
StringBuilder sb = new StringBuilder(length);
sb.append(court).append(module_math);
String res = sb.toString();
System.out.println(res);
/* StringBuilder */
length = court.length()+module_math.length();
StringBuffer sBuffer = new StringBuffer(length);
sb.append(" and").append(court).append(module_res);
res = sb.toString();
System.out.println(res);
}
Math Courtyard
Math Courtyard and Network Courtyard
Performance of String Concatenation in Java
It is clear that the easiest and fastest way to concatenate Strings is to use the '+' operator and it works very well when you just have two strings, but if you need to concatenate thousands of strings and especially inside a loop, then the performance will decrease with the '+' operator. The cause of the poor performance is the creation of temporary batches for String objects. If you have a lot of Strings in your program, you can see the results below that show that the best way for large-scale concatenation is to use the StringBuilder. These statistics were made in a Windows 7 64-bit environment, Core 2 Duo processor (2.53 GHz) with 4 GB of RAM.public static void main(String[] args) {Results for 10000 concatenation operations:
int nb_op=10000;
String s="";
double t1,t2,time;
t1= System.currentTimeMillis();
for(int i = 0 ; i < nb_op; i++)
s += "*";
t2 = System.currentTimeMillis();
time = t2-t1;
System.out.println("+: "+time);
s="";
t1= System.currentTimeMillis();
for(int i = 0 ; i < nb_op; i++)
s.concat("*");
t2 = System.currentTimeMillis();
time = t2-t1;
System.out.println("concat: "+time);
StringBuilder sb=new StringBuilder();
t1= System.currentTimeMillis();
for(int i = 0 ; i < nb_op; i++)
sb.append("*");
t2 = System.currentTimeMillis();
time = t2-t1;
System.out.println("StringBuilder: "+time);
StringBuffer sBuffer=new StringBuffer();
t1= System.currentTimeMillis();
for(int i = 0 ; i < nb_op; i++)
sBuffer.append("*");
t2 = System.currentTimeMillis();
time = t2-t1;
System.out.println("StringBuffer: "+time);
}
+: 180.0
concat: 13.0
StringBuilder: 2.0
StringBuffer: 4.0
![]() |
Time in milliseconds for 10000 operations |
The first impression is amazing! Here we immediately notice that the time achieved by the operator '+' is proportional with the number of concatenation operations and it has done ten seconds for 100000 operations. So the '+' operator is a very bad choice when working on a large-scale project. concat, StringBuilder and StringBuffer are invisible to the '+' operator, but you can see in the statistics table that StringBiulder took less time.
The method concat() is fast. However, the concatenation of multiple strings is done faster with the StringBuilder method in terms of performance.
The source code for String and StringBuilder is available in the Sun JDK. You can see that you are building a tank board. Its memory allocation is super fast.
Remember:
- Never use the operator + in a loop.
- Always use StringBuilder for concatenating multiple Strings.
- Always initialize the size of StringBuilder.
Java - String concat() Method
String concatenation: concat() vs + operator
Java - String Buffer append() Method