Table of contents
1.
Introduction
2.
What is a String?
2.1.
Java
3.
How to string concatenate in Java?
4.
Java String Concatenation
5.
Java String + operator
5.1.
Example 1
5.2.
Java
5.3.
Example 2
5.4.
Java
6.
Java String concat() method
6.1.
Syntax
6.2.
Example
6.3.
Java
7.
Java String append() method
7.1.
Syntax
7.2.
Example
7.3.
Java
8.
Java String format() method
8.1.
Syntax
8.2.
Example
8.3.
Java
9.
Java String join() method
9.1.
Syntax
9.2.
Example
9.3.
Java
10.
Java String add() method
10.1.
Example
10.2.
Java
11.
Collectors.joining() method
11.1.
Example
11.2.
Java
12.
Java String Using StringBuilder class
12.1.
Why Use StringBuilder?
12.2.
Example of Using StringBuilder
12.3.
Java
13.
Frequently Asked Questions
13.1.
Does += work with strings in Java?
13.2.
How to concatenate four strings in Java?
13.3.
How do you concatenate a string formula?
14.
Conclusion
Last Updated: Nov 11, 2024
Easy

String Concatenation in Java

Author Nagendra
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

String concatenation is a fundamental operation in Java, essential for combining text and other data types into a single string. Whether you’re building user interfaces, formatting reports, or logging information, concatenation helps streamline these processes by combining strings efficiently. Java provides multiple ways to concatenate strings, from the simple + operator to powerful classes like StringBuilder and StringJoiner. Each method has strengths, and knowing when to use them can optimize performance, especially in large applications. In this blog, we'll explore different ways to concatenate strings in Java.

String Concatenation in Java

Also see, Duck Number in Java and Swap Function in Java

What is a String?

The String is an immutable class, which means that its object can't be changed after it's been formed, although it can reference other objects. Immutable objects are thread-safe in multithreading environments because many threads cannot change the object's state. Arrays are unchangeable in Java, and strings are as well. In any instance, if a string is modified, a whole new string is created.

Some facts about Strings are : 

  • The index of strings starts from 0.
  • String objects are immutable.

Take a look at the example below to see how to concatenate a string.

Code

  • Java

Java

public class String_Conacatenation {
  public static void main(String args[]) {
     String s = "String";
     s = s + " Concatenation";
     System.out.println(s);
  }
}
You can also try this code with Online Java Compiler
Run Code

Output

String Concatenation

Explanation:

The ‘+’ operator concatenates the String.

Let's continue by learning different ways to concatenate strings.

You can also read about the topic of Java Destructor and Hashcode Method in Java.

How to string concatenate in Java?

There are different ways to concatenate strings in Java:

  1. Using the + Operator: This is the simplest way to concatenate strings, where the + operator is used to add strings together. However, it’s not ideal for performance when used extensively, as it creates a new string object each time.
  2. Using String.concat(): This method is part of the String class and only works with strings. It appends one string to another without supporting other data types. It performs similarly to the + operator, with similar limitations in terms of creating new objects each time it’s used.
  3. Using StringBuilder or StringBuffer: These classes allow mutable strings, meaning they don’t create a new object each time they are modified. This makes them efficient for repeated or large concatenations, especially within loops. StringBuilder is faster but not thread-safe, while StringBuffer is thread-safe but slightly slower.
  4. Using String.join(): Available since Java 8, String.join() allows strings to be joined with a specified delimiter. This method is concise and useful when you need to join multiple strings with a consistent separator, especially when dealing with arrays or lists.
  5. Using String.format(): This method lets you format text by inserting variables into a template. It’s ideal when you need formatted or structured text, as it improves readability and flexibility. However, it’s slower than StringBuilder for large or frequent concatenations.
  6. Using Collectors.joining(): Part of Java 8’s Stream API, this method allows concatenating all elements in a collection (like a list) with optional delimiters, prefixes, and suffixes. It’s particularly useful for collections, providing a clean and functional approach.

Java String Concatenation

A number of methods for string concatenation are available in the Java String class and Java StringBuffer class. The following are a few of the most commonly utilised methods:

  • + operator
  • concat() method
  • append() method
  • format() method
  • join() method
  • add() method
  • Collectors.joining() method

Let's get into each method in detail.

Java String + operator

The + operator is the most common method for concatenating two strings in Java. A variable, a String, or a number literal can all be used.

Take a look at the example below to see how to concatenate a string.

Example 1

With the help of the following code snippet, we will see the working of + operator.

Code

  • Java

Java

public class String_Conacatenation {
  public static void main(String args[]) {
     String s = "String";
     s = s + " Concatenation";
     System.out.println(s);
  }
}
You can also try this code with Online Java Compiler
Run Code

Output

String Concatenation

Explanation:

The ‘+’ operator concatenates the String.

The StringBuilder (or StringBuffer) class and its add function are used to concatenate strings in Java. By attaching the second argument to the end of the first operand, the String concatenation operator creates a new String. Not just Strings but also primitive items can be concatenated using the String concatenation operator.

Example 2

Consider the following scenario:

Code

  • Java

Java

public class String_Conacatenation {
  public static void main(String args[]) {
   String s=10+80+"String"+40+40; 
   System.out.println(s);
  }
}
You can also try this code with Online Java Compiler
Run Code

Output

90String4040

Explanation

All + characters after a string literals are treated as string concatenation operators.

Java String concat() method

The String concat() method concatenates the specified String with the end of the current String.

Syntax

The following is the syntax of concat() method :

public String concat (String str)​ 

Let's look at an example to help us grasp it better.

Example

With the help of the following code snippet, we will see the working of concat() method.

Code

  • Java

Java

public class String_Conacatenation 
{
  public static void main(String args[])
  {
     String s = "String";
     String s1 =" Concatenation";
     System.out.println(s.concat(s1));
  }
}
You can also try this code with Online Java Compiler
Run Code

Output

String Concatenation

Explanation

The concat() method concatenates the first String with the second String.

Java String append() method

The append() function of the StringBuilder class is used to conduct concatenation operations. Objects, StringBuilder, int, char, CharSequence, boolean, float, and double inputs are all accepted by the append() method. In Java, StringBuilder is the most popular and fastest method of concatenating strings. Because it is a mutable class, values saved in StringBuilder instances can be updated or changed.

Syntax

The following is the syntax of append() method :

public StringBuilder append(String str)

Let's look at an example to help us grasp it better.

Example

With the help of the following code snippet, we will see the working of the append() method.

Code

  • Java

Java

public class String_Conacatenation 
{
  public static void main(String args[])
  {
     StringBuilder s = new StringBuilder("String");
     StringBuilder s1 = new StringBuilder(" Concatenation");
     System.out.println(s.append(s1));
  }
}
You can also try this code with Online Java Compiler
Run Code

Output

String Concatenation

Explanation

Here, s and s1 are specified as StringBuilder class objects. The result of the append() method's concatenation of s and s1 is printed.

Java String format() method

The String.format() method allows you to concatenate multiple strings using format specifiers such as percent (%s) and string values or objects.

Syntax

The following is the syntax of format() method :

public static String format(String format, Object... args) 

Let's have a look at an example to better understand it.

Example

With the help of the following code snippet, we will see the working of format() method.

Code

  • Java

Java

public class String_Conacatenation {
  public static void main(String args[]) {
     String s = "String";
     String s1 =" Concatenation";
     String s2 =String.format("%s%s",s,s1);
     System.out.println(s2);
  }
}
You can also try this code with Online Java Compiler
Run Code

Output

String Concatenation
You can also try this code with Online Java Compiler
Run Code

Explanation

The String.format() method is used to assign the concatenated result of Strings s and s1 to the String s2. The format() method accepts format specifiers followed by String objects or values as parameters.

Java String join() method

The String.join() function is present in Java 8 and all versions above. The method String.join() takes two arguments: a separator and an array of String objects.

Syntax

The following is the syntax of join() method :

public static String join(CharSequence delimiter, CharSequence... elements)  

Let's have a look at an example to better understand it.

Example

With the help of the following code snippet, we will see the working of join() method.

Code

  • Java

Java

public class String_Conacatenation {
  public static void main(String args[]) {
     String s = "String";
     String s1 =" Concatenation";
     String result = String.join("",s,s1);
     System.out.println(result);
  }
}
You can also try this code with Online Java Compiler
Run Code

Output

String Concatenation

Explanation

The String object ‘result’ in the following code sample stores the result of the String.join(", "s,s1) function. Within quotation marks, a separator is supplied, followed by the String objects or array of String objects.

Java String add() method

All of the functionality of the String.join() method is available in the StringJoiner class. Its constructor can also accept optional arguments, such as suffix and prefix, in advance. 

Let's have a look at an example to better understand it.

Example

With the help of the following code snippet, we will see the working of add() method.

Code

  • Java

Java

import java.util.*;
public class String_Conacatenation {
  public static void main(String args[]) {
       StringJoiner s = new StringJoiner(" "); // separator is passed as argument
       s.add("String"); //String 1 
       s.add("Concatenation"); //String 2 
       System.out.println(s);
  }
}
You can also try this code with Online Java Compiler
Run Code

Output

String Concatenation

Explanation

The StringJoiner object s is declared in the preceding code sample, and the constructor StringJoiner() accepts a separator value. Within quotation marks, a separator is defined. Strings supplied as arguments are appended using the add() function.

Collectors.joining() method

In Java 8, the Collectors class has a joining() method that concatenates the input components in the same order as they appear.

Let's have a look at an example to better understand it and Practice it on online java compiler.

Example

With the help of the following code snippet, we will see the working of Collectors.joining() method.

Code

  • Java

Java

import java.util.*;
import java.util.stream.Collectors;
public class String_Conacatenation
{
  public static void main(String args[])
  {
     List<String> liststr = Arrays.asList("String", "Concatenation"); //Strings list
   String str = liststr.stream().collect(Collectors.joining(" ")); //joining operation 
       System.out.println(str); //Displays result
  }
}
You can also try this code with Online Java Compiler
Run Code

Output

String Concatenation

Explanation

A String array list is declared here. The outcome of the Collectors.joining() method is stored in a String object str and is printed.

Java String Using StringBuilder class

In Java, the StringBuilder class is commonly used to manipulate strings efficiently, especially when working with a lot of concatenations or in performance-sensitive areas. Unlike the String class, which is immutable (meaning it cannot be modified once created), StringBuilder allows strings to be changed without creating new objects each time, making it faster and more memory-efficient for repeated modifications.

Why Use StringBuilder?

Every time you concatenate strings using the + operator or concat() method on String, Java creates a new string object. This can become inefficient in loops or situations where multiple concatenations are needed. StringBuilder avoids this by using a mutable buffer to make changes to the string directly.

Example of Using StringBuilder

Here's a simple example to demonstrate how StringBuilder works:

  • Java

Java

public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");

// Appending strings
sb.append(" World"); // Appends " World" to "Hello"
sb.append("!");
System.out.println(sb); // Output: "Hello World!"

// Inserting text at a specific position
sb.insert(6, "Java "); // Inserts "Java " at index 6
System.out.println(sb); // Output: "Hello Java World!"

// Replacing part of the string
sb.replace(6, 10, "Amazing"); // Replaces "Java" with "Amazing"
System.out.println(sb); // Output: "Hello Amazing World!"

// Deleting part of the string
sb.delete(6, 14); // Deletes "Amazing " from the string
System.out.println(sb); // Output: "Hello World!"

// Reversing the string
sb.reverse();
System.out.println(sb); // Output: "!dlroW olleH"

// Converting StringBuilder to String
String finalString = sb.toString();
System.out.println("Final String: " + finalString); // Output: "!dlroW olleH"
}
}
You can also try this code with Online Java Compiler
Run Code

Frequently Asked Questions

Does += work with strings in Java?

Yes, += works with strings in Java, allowing you to append one string to another by combining them into a new string.

How to concatenate four strings in Java?

You can concatenate four strings in Java using the + operator, concat() method, or StringBuilder for optimal performance in larger applications.

How do you concatenate a string formula?

To concatenate a formula as a string, use +, StringBuilder, or String.format() to dynamically combine text, variables, and expressions.

Conclusion

In this article, we have extensively discussed the String Concatenation along with different approaches used for String concatenation along with their syntax and examples.
We hope that this blog has helped you enhance your knowledge regarding the String concatenation, and if you would like to learn more, check out our articles on Java. You can refer to our guided paths on the Code360 platform to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. To practice and improve yourself in the interview, you can also check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews.

Also check out - String Interview Questions In Java

Recommended problems -

Live masterclass