C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Result: The string, named "result," contains the character data from the two string, combined into one string.
Java program that uses concat, 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);
}
}
Output
ABCDEF
Warning: Using concat excessively can cause poor performance. Often by coalescing concats we can get better speed.
And: Using StringBuilder to combine strings together, as in a loop, is a still better choice in many programs.
ForJava program that uses concat chained method calls
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);
}
}
Output
123456789
Java program that uses concat, plus sign
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);
}
}
Output
abracadabra
Java program that appends strings with plus operator
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);
}
}
Output
cat1010dog
Note: With StringBuilder, we avoid creating a string after each change. Only a mutable buffer is changed.
So: StringBuilder is an effective optimization for complex things, but for few appends it is no better—it may even be slower.
StringBuilder