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 Format Symbols

You can customize which symbols are used as decimal separator, grouping separator, currency seperator etc. using a DecimalFormatSymbols instance together with java.text.DecimalFormat class. The...

How To Convert List To Array in Java

A common scenario faced by programmers is to convert a Java List to an Array. A 'List' is part of the Collection Framework and...

How To Create Maven Project in Eclipse With Archetype

Maven Basics Maven automates the steps involved in building a software application like adding the JAR files, compiling code, running unit tests, creating the output...

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

Â

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 Install WordPress Locally using XAMPP

1. Introduction Installing WordPress on your computer helps you try out WordPress, test themes and plugins, and learn WordPress development.  It lets you operate a...

How To Install Pacman For Git on Windows

The 'Git for Windows' by default does not come with MSYS2 package manager called 'Pacman' and hence it is a limited version or subset...

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

Remove Duplicates from List Using HashSet

The Set is also an interface in the 'Java Collection' framework. Unlike a List, a Set does not allow duplicates. Hence you can...

CHECKOUT TUTORIALS

Java Tutorial #2 – Operators in Java

Table of Contents Introduction 1. Assignment Operator 2. Arithmetic Operators 3. Compound Operators 4. Increment & Decrement Operators 5. Relational Operators 6. Logical Operators Introduction Operators are an essential...
- Advertisement -spot_img