How To Concatenate Strings in Java

Table of Contents

Introduction

In Java, a String is a sequence of characters. There are often programming situations where you will need to concatenate Strings. There are several ways in which you can achieve this. In the next few sections, I will be going over each method in detail.

Using + Operator

The + operator is also known as the concatenation operator. It can be used to concatenate Strings. The following code demonstrates this:

private static void usingPlusOperator() {
String string1 = "Hello ";
	String string2 = "World";
	String result = string1+string2;
	System.out.println(result);
}

This code creates two Strings called string1 and string2. It uses the + operator to concatenate them and assign the result to a separate variable. So, this code prints the following output:

Hello World

This approach can be used to concatenate more than two values. Not only that, it can be used to concatenate other types of values like primitives as shown below:

String result = “Hello”+” World”+” 2“+” times!”; 

So, this code prints the following output:

Hello World 2 times!

The downside of this approach is that it is not very efficient. Since String is immutable, every time you use the + operator, a new String is created.

Using String.concat

The String class has a method called concat. It accepts as parameter a String value and concatenates it with the current String. The following code demonstrates this:

private static void usingStringConcat() {
	String string1 = "Hello ";
	String string2 = "World";
	String result = string1.concat(string2);
	System.out.println(result);
}

As before, this code creates string1 and string2.  It then invokes the concat() method on string1 and passes string2 as an argument. So, this code also prints the same output as before:

Hello World

Performance-wise, this approach is not much better than using the + operator. Also, unlike the + operator, this approach cannot be used for multiple Strings or other types of values.

Using StringBuffer/StringBuilder

In addition to String, Java has the java.lang.StringBuffer and java.lang.StringBuilder classes. These can also be used to concatenate Strings.  The advantage of these classes is that both these classes are mutable, so using them does not result in the creation of new String objects. So StringBuffer and StringBuilder have a better performance as compared to the + operator and concat method.

Using StringBuffer for Strings

The StringBuffer class has a method called append which can be used to concatenate Strings. It appends the value passed in with the StringBuffer on which it is invoked. The following code demonstrates this:

private static void usingStringBuffer() {
String string1 = "Hello ";
	String string2 = "World";
	StringBuffer result = new StringBuffer();
	result.append(string1);
	result.append(string2);
	System.out.println(result);
}

As before, this code creates string1 and string2.  It also creates a StringBuffer called result. It then invokes the append method with both the Strings. So, this code also prints the same output as before: Hello World

Using StringBuffer for other types of data

There are several overloaded versions of the append method that accept data of different types like primitive values, character arrays and Strings. These methods can be used to append different types of data as demonstrated below:

StringBuffer result = new StringBuffer();
result.append("Hello").append(" World ").append(2).append(" times!");

So, this code prints the following output: Hello World 2 times!

Using StringBuilder

The StringBuilder class is very similar to StringBuffer. It also has a method called append which can be used to concatenate Strings. The only difference is that StringBuffer is synchronised while StringBuilder is not. So StringBuilder has a slight performance advantage over StringBuffer.

The following code demonstrates the StringBuilder.append method:

private static void usingStringBuilder() {
String string1 = "Hello ";
	String string2 = "World";
	StringBuilder result = new StringBuilder();
	result.append(string1);
	result.append(string2);
	System.out.println(result);
}

So, this code is exactly the same as the StringBuffer code and it prints the following output: Hello World

Using String.join

Java 8 has added a static join method to the String class. This concatenates Strings using a delimiter. Performance-wise, it is similar to StringBuffer.append, but it has the added advantage that it automatically adds a delimiter.

String.join for multiple Strings

 The String.join() method accepts as parameter a variable number of Strings that need to be concatenated as well as a delimiter to separate the Strings. The following code demonstrates this:

private static void usingStringJoin() {

String string1 = "red";
	String string2 = "blue";
	String result = String.join(" ", string1,string2);
	System.out.println(result);

}

As before, this code creates string1 and string2.  It invokes the join method with these Strings and specifies space (“ “) as a delimiter. So, this code prints the following output: red blue

String.join for a Collection

There is also an overloaded version of the String.join method that accepts as parameter an Iterable implementation. Since all Collection classes implement the Iterable interface, this method can be used to concatenate all the elements in a Collection. The following code demonstrates this:

private static void usingStringJoinWithList() {

List<String> colours = Arrays.asList("red","blue","green","white");
	String result = String.join("/", colours);
	System.out.println(result);

}

This code creates a List of String values and passes this List to the String.join method with a “/” as the delimiter. So, this code prints the following output: red/blue/green/white

Using StringJoiner

Java 8 has added a new class called StringJoiner. This concatenates Strings using a delimiter as well as adds a prefix and suffix to the concatenated String. Performance wise, it is similar to StringBuffer.append, but it has the added advantage that it automatically adds a delimiter, prefix and suffix.

The following code demonstrates how the StringJoiner class can be used to concatenate Strings:

private static void usingStringJoiner() {

	StringJoiner strJoiner = new StringJoiner(",","{","}");	strJoiner.add("red");
	strJoiner.add("blue");
	strJoiner.add("green");
	System.out.println(strJoiner);

}

This code creates a StringJoiner. It specifies that a comma symbol (,) should be used as the delimiter. It also specifies that the “{“should be used as the prefix and “}” should be used as the suffix. It then invokes the add method with some String values. So, this concatenates the specified Strings using the specified delimiter, prefix and suffix. So, this code prints the following output: {red,blue,green}

Conclusion

So, as seen in this article, there are several ways in which you can concatenate Strings in Java. The approach that you need to choose depends on your requirements and performance consideration. If you want to simply concatenate Strings without a delimiter, using a StringBuffer or StringBuilder is a better approach. However, if you want to add delimiters/prefix/suffix, consider going for the String.join or StringJoiner method.  

Tushar Sharma
Tushar Sharmahttps://www.automationdojos.com
Hi! This is Tushar, the author of 'Automation Dojos'. A passionate IT professional with a big appetite for learning, I enjoy technical content creation and curation. Hope you are having a good time! Don't forget to subscribe and stay in touch. Wishing you happy learning!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

RELATED POSTS

Remove Duplicates from List Using LinkedHashSet

Another implementation of the Set interface is LinkedHashSet. LinkedHashSet maintains the order of elements and helps to overcome the HashSet limitation. The following code...

How To Create Maven Project in Eclipse Without Archetype

Maven is a very popular build and dependency management tool. Eclipse is an IDE that helps developers write and run Java code easily. In...

Java Tutorial #5 – Loop Statements

Iteration statements are used to repeat a particular block of code until a certain condition is true. In this article, we will be taking...

Convert String to Date Using SimpleDateFormat Class

Sometimes, you may need to convert a String to a java.util.Date object. For this, you need to use the SimpleDateFormat class. You need to...

Â

RECENT 'HOW-TO'

How To Install Oh-My-Posh On Windows PowerShell

Oh-My-Posh is a powerful custom prompt engine for any shell that has the ability to adjust the prompt string with a function or variable. It does not...

MORE ON CODEX

MORE IN THIS CATEGORY

How to View Java API Doc Hints within IntelliJ

IntelliJ Quick Documentation So how do you generally refer your Java API Doc? If you use Google or online Java API Doc or even a...

Format Decimal Numbers Using Locale

If you want to create a DecimalFormat instance for a specific Locale, create a NumberFormat and cast it to a DecimalFormat. The java.text.DecimalFormat class is...

Convert List to Array Using Stream with Param

There is an overloaded version of the Stream.toArray method which can be used to return a result array that is of the same data...

Configuring Maven Compiler Plugin (Java)

1. What is Maven Compiler Plugin The ‘Maven Compiler Plugin’ or more commonly known as 'Maven Java Compiler' is used to compile the source code...

CHECKOUT TUTORIALS

Java Tutorial #6 – Jump Statements

Introduction The break statement is used to stop further execution. It can be used either in a loop or within a switch statement. Break Statement The break...

Working with JMeter Listeners

- Advertisement -spot_img