In this Q&A, we'll go over the options within Java to concatenate two or more Strings. Please note that String class is immutable. All options create a new character buffer and copy characters,
Option I - Use + operator
Java provides a special + operator to concatenate Strings.
Option II - Use StringBuilder
StringBuilder is a mutable character set. One can append character sets to the buffer and eventually create a string object using toString() method.
Option III - Use StringBuffer
StringBuffer is similar to StringBuilder. Its a synchronized, thread-safe cousin of StringBuilder
Option IV - Using String.concat
String class provides a method to concatenate two strings. It creates a new buffer, concatenates two character buffers and returns a new String object
Option V and VI - Using String.join method or StringJoiner class
String.join() method and StringJoiner class provide functionality to concatenate Strings or Array of Strings along with a delimiter.
Most roads lead to StringBuilder
In Java 8, in addition to option II, options I, V, VI eventually use StringBuilder to concatenate character buffers. Options I, V, VI add a small layer of functionality over StringBuilder.
Demo code
package com.javahowdoi.string;
import java.util.StringJoiner;
import static junit.framework.TestCase.assertEquals;
public class ConcatDemo {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "world";
// Option I
String s3 = s1 + s2;
assertEquals("helloworld match", "helloworld", s3 );
// Option II
StringBuilder sb = new StringBuilder(32);
s3 = sb.append(s1).append(s2).toString();
assertEquals("helloworld match", "helloworld", s3 );
// Option III
StringBuffer sb1 = new StringBuffer();
s3 = sb1.append(s1).append(s2).toString();
assertEquals("helloworld match", "helloworld", s3 );
// Option IV
s3 = s1.concat(s2);
assertEquals("helloworld match", "helloworld", s3 );
// Option V
s3 = String.join("", s1, s2);
String[] l = {s1, s2};
assertEquals("helloworld match", "helloworld", s3 );
// Option VI
StringJoiner j = new StringJoiner("", s1, s2);
s3 = j.toString();
assertEquals("helloworld match", "helloworld", s3 );
}
}
Comments
Post a Comment