×

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) operator
  • By concat() method
  • By + (String concatenation) operator

Java String concatenation operator (+) is utilised to join strings.

Example:

class Example{  
//main method
 public static void main(String args[]){  
//declaring string with str 
  String str="North"+" America";  
  System.out.println(str);  
 }  
}  

Output:

North America

Functioning of the above code:

String str=(new StringBuilder()).append("Uttar").append(" Pradesh).toString();  

In Java, String concatenation is executed via the StringBuilder (or StringBuffer), an append method. The string concatenation operator creates a new string by adding the second operand to the ending of the first operand. This operator can join not only String but primitive values likewise. 

Example:

class Example2{  
 public static void main(String args[]){  
     String str=20+30+"AddOperation"+20+40;  
     System.out.println(str);//
 }  
}  

Output:

50AddOperation2040

Note: Behind a string literal, every (+) will be considered a string concatenation operator.

  • By concat() method

This method attaches the stipulated String to the ending of the existing String.

Syntax:

public String concat(String another)  

Example:

Now, have a look at an eample of the String concat() method.

class Example{  
 public static void main(String args[]){  
  String str="North ";  
  String str2="America";  
  String str3=s1.concat(s2);  
  System.out.println(str3);
  }  
}  

Output:

North America

We can conclude that the illustrated Java program joins two String objects, str and str1, with the help of the concat() method and returns the result in the str3 object.

We have several other methods to concatenate strings in Java.

1. String concatenation with the help of StringBuilder class

It is a class that delivers the append() method to achieve concat operations. The append () method abides by various arguments such as Object, StringBuilder, int, char, CharSequence, boolean, float, and double. StringBuilder is the very common and fastest manner to connect strings in Java. It is a variable class. You can update or transform the values kept in the StringBuilder object.

Example:

public class Example  
{  
   public static void main(String args[])  
   {  
     StringBuilder str = new StringBuilder("Java"); //String 1  
     StringBuilder str1 = new StringBuilder(" Tutorial"); //String2  
     StringBuilder str2 = str1.append(str2); //To store the result  
       System.out.println(str3.toString()); 
   }  
}  

Output:

Java Tutorial

In the above code snippet, str1, str2 and str3 are declared objects of the StringBuilder class. s stores the result of the concatenation of str1 and str2 using the append() method.

2. String concatenation using format() method

String.format() method permits concatenating numerous strings utilising format specifiers like %s heeded by the string values or objects.

Example:

public class Example4 
{  
   public static void main(String args[])  
   {  
     String str1 = new String("Java"); //String 1  
     String str2 = new String(" Tutorial"); //String 2  
     String str3 = String.format("%str3%str3",str1,str2); //String 3 to store the result  
       System.out.println(str3.toString());  
   }  
}  

Output:

Java Tutorial

Here, the String objects str3 are assigned the concatenated result of Strings str1 and str2 using the String.format() method. format() takes parameters as format specifiers heeded by String objects or values.

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

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

Example:

public class StrJoin
{
public static void main (String args [])
{
String str1 = new String ("Java"); // String 1
String str2 = new String ("Tutorial"); // String 2
String str3 = String.join (" ", str1, str2); // String to store the result 3
System.out.println (str3.toString ());
}
}

Output:

Java Tutorial

Above In the code snippet, the String object str3 stores the result of the String.join(" ", str1, str2) method. The delimiter is specified by quotation marks, followed by a String object or an array of String objects.

4. String concatenation using StringJoiner class (Java Version 8+)

The StringJoiner class has all the functionality of the String.join() method. In advance, its constructor can also accept optional arguments, prefixes, and suffixes.

Example:

public class StrJoiner
{
public static void main (String args [])
{
StringJoiner str1 = new StringJoiner (","); // StringeJoiner object
str1.add ("Java"); // String 1
str1.add ("Tutorial"); // String 2
System.out.println (str1.toString ());
}
}

Output:

Java, Tutorial

The StringJoiner object str1 is declared and constructed in the above code snippet. The stringJoiner () accepts the separator value. Specify the delimiter by enclosing it in quotation marks. The add () method adds the String passed as an argument.

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

Java8 Collectors class concatenates and receives input elements in the same order as they occur. 

Example:

import java.util.*;  
import java.util.stream.Collectors;  
public class LastExample
{  
   public static void main(String args[])  
   {  
     List<String> liststr = Arrays.asList("This", "is", "tutorialandexample"); //List of String array 
   String abc = liststr.stream().collect(Collectors.joining(", ")); //Perform the connection operation 
     System.out.println(abc.toString()); //Display the result  
   }  
}  

Output:

this, is, tutorialandexample

A list of string arrays is declared here. Also, the String object abc stores the result of the Collectors.joining() method.


Related Topics

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be...

6 minutes read.

Kotlin Vs Java

Kotlin Vs Java There are many languages available for Android development. Java is the official language for android development but Kotlin is becoming popular nowadays. This article discusses both of these...

4 minutes read.

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

3 minutes read.

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

Sleep Time in Java

Sleep is amethod in java that is related to thread class and it is a concept of multithreading and is used to stop the execution of the current thread a...

4 minutes read.

How to Solve the Deprecated Error in Java?

Deprecated Java methods should not be used because they are deprecated (often, there are better, more modern alternatives). API update. Until now, Java has kept everything backward compatible and never...

3 minutes read.

Difference between Aggregation and Composition in Java

What is Aggregation? Before we start discussing Aggregation, we have to know some general information about our classes in java. Generally we have two members in our classes , the first...

8 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Difference Between Thread.start() and Thread.run()

In the Java programming language, the multi-threading concept consists of the start() and run() methods. Thread.start(): The thread's execution is initiated by invoking the start() method. The start() method operates two threads...

4 minutes read.

Bedrock vs Java

The popularity of Minecraft, a sandbox video game, has skyrocketed. The scope, level of complexity, and variety of gameplay in this game are enormous, and user-generated content has helped to...

4 minutes read.

Tilt operator in Java | Tilde operator in Java Example

The symbol designates it as a unary operator (pronounced as the tilde). It gives back the bit's complement or inverse. Every 0 turns into a 1, and every 1 back...

3 minutes read.

Unicode System in Java

In this tutorial, we will understand the meaning and emergence of the Unicode system in java. The Unicode system is one of the important and useful features in the world...

6 minutes read.

Order of Execution of Constructors in Java Inheritance

Constructor in Java There are several distinctions between a method and a function object() in Java. The name of the function object()  is identical to the class name. There is no...

4 minutes read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.

Java Polymorphism

The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means...

5 minutes read.

Getting the Day from the Date in Java?

To extract the day's name from the date, we will write Java application. When dealing the date and time in Java, the following classes are used. Class for Calendars: This class is...

6 minutes read.

Java Try-Catch Block

Java Try Block The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a...

3 minutes read.

Self-Descriptive Numbers in Java

A number n is given. Identifying the self-descriptive numbers that exist between 1 and n is our task. Self-Descriptive Numbers The definition of a self-descriptive number, m, is a number with b...

6 minutes read.

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements. Example:  Input: a [ ] = {2 , 4 , 6...

3 minutes read.

Hello Program in Java

Hello Program in Java The Hello program in Java displays the word Hello on the console. It is the basic program in Java. In this section, we will learn different ways...

3 minutes read.