In Java, you can concatenate multiple strings with StringBuilder, StringBuffer, String's concat(String)
method or +
operator (ordered by performance preference)
Using StringBuilder
You can use StringBuilder's append
or insert
method to concatenate strings. They are overloaded to accept any data type. While append
method always adds the string at the end of the builder, the insert
method adds the string at a specified index
Instances of StringBuilder
are not safe to be used by multiple threads. In that case, consider using StringBuffer
@Test
public void givenMultipleDataTypes_whenConcatByStringBuilder_thenSuccess() {
StringBuilder sb = new StringBuilder();
sb.append("Hello ");
sb.append("Koding ");
sb.append(2015);
String result = sb.toString();
assertThat(result).isEqualTo("Hello Koding 2015");
}
Using StringBuffer
StringBuffer
has the API compatible with StringBuilder
, so you can also use append
or insert
methods of StringBuffer
to concatenate strings
StringBuffer
is designed to be used in multiple threads environment
@Test
public void givenMultipleDataTypes_whenConcatByStringBuilder_thenSuccess() {
StringBuffer sb = new StringBuffer();
sb.append("Hello ");
sb.append("Koding ");
sb.append(2015);
String result = sb.toString();
assertThat(result).isEqualTo("Hello Koding 2015");
}
Using String's concat(String) method
The Java String
class provides the concat(String)
method to concatenate the specified string to the end of the caller string
The concat
method only accept String
data type, so try converting the argument to String
before passing to the method
@Test
public void givenMultipleDataTypes_whenConcatByStringConcat_thenSuccess() {
int foundedYear = 2015;
String result = "Hello ".concat("Koding ").concat(Integer.toString(foundedYear));
assertThat(result).isEqualTo("Hello Koding 2015");
}
Using +
operator
The Java +
operator will try to convert the input parameters to String before concatenation. It offers convenient typing but with slowest performance as a new String object will be created on every operations
@Test
public void givenMultipleDataTypes_whenConcatByPlus_thenSuccess() {
int foundedYear = 2015;
String result = "Hello " + "Koding " + foundedYear;
assertThat(result).isEqualTo("Hello Koding 2015");
}
Conclusion
In this tutorial, we learned various methods to concatenate strings in Java. While String's concat and +
operator are used in simple cases, StringBuilder
is recommended to be used when you want to care about the performance. The full source code can be found as below