Concat
Two Java strings can be combined with concat. A new string
, one with the new data appended, is returned. This can cause performance problems.
With concat, and the plus operator, we use two strings to create a third one. When many appends occur, StringBuilder
is often a better, faster choice.
This program uses concat: it takes the initial string
"ABC" and concats "DEF". Concat
adds (or appends) to the end of the string
.
string
, named "result," contains the character data from the two string
, combined into one string
.public class Program { public static void main(String[] args) { String value = "ABC"; // Concat another string. String result = value.concat("DEF"); // Display the result. System.out.println(result); } }ABCDEF
Concat
, chainThe result of concat()
is a new String
. We can call concat again on this string
reference. The resulting, final string
, is created by the evaluation of all chained methods.
StringBuilder
to combine strings together, as in a loop, is a still better choice in many programs.public class Program { public static void main(String[] args) { String value = "123"; // Call concat twice in one statement. String result = value.concat("456").concat("789"); System.out.println(result); } }123456789
Concat
can be called through the plus sign. This operator invokes the concat()
method. Less typing is required. The syntax may be clearer to read for some developers.
public class Program { public static void main(String[] args) { String value1 = "abra"; String plus = "ca"; String value2 = "dabra"; // The strings can be concatenated with a plus sign. String result = value1 + plus + value2; System.out.println(result); } }abracadabra
With the "+=" operator we can append a string
. This is the same as concat, but the result of concat is assigned to the variable. We can use many appends in order.
public class Program { public static void main(String[] args) { // Append two strings to the initial value. String value = "cat"; value += "10"; value += "10"; // Append a String variable. String animal = "dog"; value += animal; System.out.println(value); } }cat1010dog
StringBuilder
We mentioned StringBuilder
as a possible optimization for concat. This is effective when we concat in nontrivial loops.
StringBuilder
, we avoid creating a string
after each change. Only a mutable buffer is changed.StringBuilder
is an effective optimization for complex things, but for few appends it is no better—it may even be slower.With concat or the plus sign, we concatenate (append) strings. This is powerful, but it may be slow in complex operations. StringBuilder
is a worthwhile alternative.