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

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...

Concatenate Strings Using Plus Operator

In Java, a String is a sequence of characters. There are often programming situations where you will need to concatenate Strings. There are several...

Format Decimal Numbers Using Pattern

The java.text.DecimalFormat class is used to format numbers using a user specified formatting. This concrete subclass of NumberFormat, allows formatting decimal numbers via predefined...

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...

Â

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

Convert List to Array Using ToArray Without Param

Java provides a toArray method on the 'List' interface. This can be used to convert a 'List' to an array. Since there are are...

Java Tutorial #7 Part 1 – Classes & Objects

Classes are a very important concept in Java. Java code always needs to be written in a class. In this article, we will be...

Early Bound Vs Late Bound (Binding)

What is Binding Before we dive into 'Early' and 'Late' stuff, let us discover, what the 'Binding' itself means? In simple terms, the 'Binding' refers to...

Concatenate Strings Using Plus Operator

In Java, a String is a sequence of characters. There are often programming situations where you will need to concatenate Strings. There are several...

CHECKOUT TUTORIALS

Java Tutorial #4 – Control Statements

Introduction Control statements are used to change the flow of execution based on changes to certain variables in the code. One of the types of...
- Advertisement -spot_img