×

Java String Concatenation

Java String Concatenation

Java programming provide a way to combine multiple strings into a single string. It is called as String Concatenation. There are different ways to concatenate two or more strings in Java.

  1. String concatenation using + operator

The arithmetic operator + is placed in between two string variables in order to concatenate those strings. The result can be stored in a third variable or we can directly print it using print statement.

StrConcat.java:

 public class StrConcate
{
    /* Driver Code */
                        public static void main(String args[])
                        {
                                                String s1 = "Hello";    //String 1
                                                String s2 = "World";    //String 2
                                                String s = s1 +  s2;      //String 3 to store the result
                                                System.out.println(s);       //Displays result
                        }
} 

Output:

Hello World

In the above code snippet, String s1 and s2 are concatenated using additionoperator (+) and the result is stored in String s.

  • String concatenation using concat() method

The concat() method returns a string object which stores the concatenated result of two different strings.

StrConcate.java:

 public class StrConcate
{
    /* Driver Code */
                        public static void main(String args[])
                        {
                                                String s1 = "Hello";    //String 1
                                                String s2 = " World";    //String 2
                                                String s = s1.concat(s2);   //String 3 to store the result
                                                System.out.println(s);  //Displays result
                        }
} 

Output:

Hello World

In the above code snippet, the String object s stores the result of s1.concat(s2) method.

  • String concatenation using StringBuilder class

StringBuilder is class provides append() method to perform concatenation operation. The append() method accepts arguments of different types like Objects, StringBuilder, int, char, CharSequence, boolean, float, double. StringBuilder is the most popular and fastet way to concatenate strings in Java. It is mutable class which means values stored in StringBuilder objects can be updated or changed.

StrBuilder.java

 public class StrBuilder
{
    /* Driver Code */
                        public static void main(String args[])
                        {
                                                StringBuilder s1 = new StringBuilder("Hello");    //String 1
                                                StringBuilder s2 = new StringBuilder(" World");    //String 2
                                                StringBuilder s = s1.append(s2);   //String 3 to store the result
                                                System.out.println(s.toString());  //Displays result
                        }
} 

Output:

Hello World

                        In the above code snippet, s1, s2 and s are declared as objects of StringBuilder class.s stores the result of concatenation of s1 and s2 using append() method.

  • String concatenation using format() method

String.format() method allows to concatenate multiple strings using format specifier like %s followed by the string values or objects.

StrFormat.java

 public class StrFormat
{
    /* Driver Code */
                        public static void main(String args[])
                        {
                                                String s1 = new String("Hello");    //String 1
                                                String s2 = new String(" World");    //String 2
                                                String s = String.format("%s%s",s1,s2);   //String 3 to store the result
                                                System.out.println(s.toString());  //Displays result
                        }
} 

Output:

Hello World

                        Here, the String objects s is assigned the concatenated result of Strings s1 and s2 using String.format() method. format() accepts parameters as format specifier followed by String objects or values.

  • String concatenation using String.join() method (Java Version 8+)

The String.join() method is available in Java version 8 and all the above versions.String.join() method accepts arguments as a separator and an array of String objects.

StrJoin.java:

 public class StrJoin
{
    /* Driver Code */
                        public static void main(String args[])
                        {
                                                String s1 = new String("Hello");    //String 1
                                                String s2 = new String(" World");    //String 2
                                                String s = String.join("",s1,s2);   //String 3 to store the result
                                                System.out.println(s.toString());  //Displays result
                        }
} 

Output:

Hello World

In the above code snippet, the String object s stores the result of String.join(“”,s1,s2) method. A separator is specified inside quotation marks followed by the String objects or array of String objects.

  • String concatenation using StringJoiner class (Java Version 8+)

StrJoiner.java

 public class StrJoiner
{
    /* Driver Code */
                        public static void main(String args[])
                        {
                                                StringJoiner s = new StringJoiner(", ");   //StringeJoiner object
                                                s.add("Hello");    //String 1
                                                s.add(" World");    //String 2
                                                System.out.println(s.toString());  //Displays result
                        }
} 

Output:

Hello World

In the above code snippet, the StringJoiner object s is declared and the constructor StringJoiner() accepts a separator value. A separator is specified inside quotation marks. The add() method appends Strings passed as arguments.

  • String concatenation using Collectors.joining() method (Java (Java Version 8+)

ColJoining.java

 public class ColJoining
{
    /* Driver Code */
                        public static void main(String args[])
                        {
                            List<String>liststr = Arrays.asList("abc", "pqr", "xyz"); //List of String array
String str = liststr.stream().collect(Collectors.joining(", ")); //performs joining operation
                        System.out.println(str.toString());  //Displays result
                        }
} 

Output:

abc, pqr, xyz

Here, a list of String array is declared. And a String object str stores the result of Collectors.joining() method.

  • Converting String array into String using Arrays.toString() method

Arrays.toString function is used to convert a String array into a String. This method has its definition inside Array class.

ArrtoString.java

 import java.util.*;
public class ArrtoString
{
    /* Driver Code */
                        public static void main(String args[])
                        {
                        String[] arrstr = {"abc", "pqr", "xyz"}; //Array of String objects
                        String str = Arrays.toString(arrstr); //performs conversion operation
System.out.println(str.toString());  //Displays result
                        }
} 

Output:

[abc, pqr, xyz]

Here, a list of String array is declared. And a String object str stores the result of Arrays.toString() method.

In this article, we have discussed different methods available to perform String concatenation in Java. For better understanding each method is explained with an example.


Related Topics

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

Java Thread Lifecycle: States and Stages

Multithreading Multithreading is one of the most important features in object-oriented programming, and this multithreading can be implemented by various object-oriented programming languages like Java, Python, and C++. A multithreaded process...

7 minutes read.

Java Program to Add Digits Until the Number Becomes a Single Digit Number

We will develop Java programme that increase a number's digit count in order to reduce it to one. The issue is also known as the digit root problem. Example Consider the case where...

3 minutes read.

Java BLOB

The two data types used in Java to store binary and big-character objects are BLOB and CLOB. In contrast to other types of data like float, int, double, etc., it...

4 minutes read.

How to remove special characters from String in Java

Strings in Java are Objects that are supported inside by a burn exhibit. Since exhibits are immutable (cannot develop), Strings are changeless too. A completely new String is made whenever...

5 minutes read.

Methods in Java

The Methods in Java are the collection of statements that are executed when the method is called. By using the methods, the complexity of writing the code decreases. The method consists...

4 minutes read.

Sliding Window Problem in Java

A sliding window is used in computer science and data science to process large datasets. It involves breaking the dataset into smaller chunks or windows and then processing it in...

6 minutes read.

Java LinkedList

LinkedList Java The Java LinkedList is used to store the elements by using a doubly linked list. It contains the duplicate items, also maintains the order of the insertion, the class...

5 minutes read.

Java Boolean compareTo() method

The compareTo() method of Java Boolean class compares the Boolean argument with the Boolean instance and returns integer value, zero, or negative 1, or positive 1 based on the result...

2 minutes read.

Java Anon Proxy

The Java Anon Proxy (JAP), also known as JonDonym, is a proxy system designed to enable Web browsing with revocable (the use of or publication under a pseudonym, a false...

4 minutes read.

Difference between String and Char Array in Java

We are heading to examine some significant differences between String and Character arrays. Both char arrays and String hold the series of characters and are utilised as a cluster of...

3 minutes read.

Java Program to Create Set of Pairs Using HashSet

HashSet in Java: HashSet is an assortment in Java that has a place with java.util bundle. It inside utilises HashMap to store components. It is an execution of the Set connection...

11 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

Arrow Operator in Java

The introduction of arrow functions in ES6 gives you a more precise approach to define JavaScript functions. We can write shorter function syntax thanks to them. Your code will be...

4 minutes read.

Facts about null in Java

Nearly all programming languages have a relationship with null. Hardly any programmers are unconcerned by null. The null has a java.lang.NullPointerException association in Java. Given that it is a class...

4 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

How many ways to create object in Java?

In this article, you will be acknowledged about the different ways to create an object in java. So far you construct an object from a class, as is common knowledge,...

6 minutes read.

3N+1 problem program in Java

The 3N+1 problem is a hypothesis in the field of abstract mathematics (not yet proven). Collectively known as the Collatz problem. This tutorial will describe about the 3N+1 problem and...

3 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.