×

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

Difference Between in Java and C++

FeatureC++JavaDefinitionC++ is a general programming language created by Bjarne Stroustrup as an extension of c language    Java is class-based, object-based, and designed to have as few implementation dependencies as...

4 minutes read.

Java Integer equals() method

The equals() method of Integer class compares the given object to the specified object. Syntax public boolean equals(Object obj) Parameters The parameter ‘obj’ represents the object to be compared with. Overrides The equals() method overrides equals...

1 minute read.

Array Slicing in Java

Array slicing is a method in Java for obtaining a subarray of a specified array. Assume a[] is an array. It contains eight items indexed from a[0] to a[7].a[] =...

3 minutes read.

Java this keyword

This Keyword in Java This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the...

8 minutes read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

How to stop execution after a certain time in Java

We will learn how to stop a long-running execution after a set amount of time in this post. We will take a look at a few alternative approaches to this...

6 minutes read.

How to Install Java on MAC

There are many possible ways to install java on mac. This article is based on the installation of java on mac. The operating system platform is Mac OS X, macOS and...

3 minutes read.

Short Circuit Logical Operators in Java

When there are two or more relational expressions in a decision-making statement, logical operators are utilized to combine them. The logical operators short circuit and not-short circuit fall into two...

5 minutes read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Java Lock

A lock is indeed a threaded synchronization technique similar to Java's synchronized blocks, however, locking can be more complex. It's not like we can completely get rid of the synchronized...

5 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

Java Boolean compare() method

The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result. Syntax public static int...

2 minutes read.

Shopping Bill in Java

Java Shopping Bill Here in this program, we are about to create a JAVA class called Products which will have some properties or attributes like prod_name (Product Name ), qty (quantity),...

4 minutes read.

Java Vs C++

Java Vs C++ Java and C++ both are Object Oriented Programming languages. Both languages are popular for competitive programming. C++ is used by many coders who have just started learning programming...

4 minutes read.

Java Integer toUnsignedString() method

The toUnsignedString() method of Java Integer class returns a string representation of the argument as an unsigned decimal value. The second syntax returns a string representation of the given argument as...

2 minutes read.

Java String valueOf() method

Java String valueOf() method converts different types of values into String. Such as : int to String, long to String, boolean to String, character to String, float to String, double to...

2 minutes read.

Java gc()

Garbage collection Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced...

4 minutes read.

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

3 minutes read.