×

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

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 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 Math signum() Method

The signum() method of Java Math class returns the signum function of the value. Syntax: public static double signum(double d)public static float signum (float d) Parameters: The parameter ‘d’ represents the floating-point value whose...

2 minutes read.

Class memory in Java

Anything specifically defined in the Java code is stored either inside the heap or the stack, which is particularly significant. Stack and heap are the two kinds of memory available...

6 minutes read.

Java String Methods

Java String Methods Java String class is the most important class of the java.lang package. It is used to handle the String related operations. It contains a lot of built-in Java...

2 minutes read.

Java String join() method

Java String join() method returns a joined String with given delimiter Syntax: public static String join(CharSequence delimeter,charSequence...elements) public static String join(CharSequence delimeter,Iterable<?extens charSequence>elements) Parameters: delimiter: char value to be added with each element elements: char value...

1 minute read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java Custom Exception

Java Custom Exception Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java...

4 minutes read.

JDK | Java Development Kit

Java Development Kit (JDK) The Java Development Kit is a software development environment used to create Java applications. The JDK includes JRE (Java Runtime Environment), an interpreter (java), a compiler (javac),...

3 minutes read.

Trim Method in String Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

3 minutes read.

What is String in Java?

What is String in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a Java...

4 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 While Loop

A while loop is used to repeatedly execute a set of statements as long as its condition evaluates to true. This loop checks the condition before it starts the execution...

1 minute read.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

Java Math cbrt() Method

The cbrt() method of Math class returns the cube root of a double value. Syntax: public static double cbrt(double a) Parameters: The parameter ‘a’ represents the value whose cube root is to be determined. Return...

2 minutes read.

Types of Bitwise Operators in Java

In this tutorial, we will learn about the various types or kinds of bitwise operators in java. Before proceeding to bitwise operators, let us know what is meant by the...

6 minutes read.

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as...

4 minutes read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

Java Math toDegrees() Method

The toDegrees() method of Java Math class converts a radian angle to an approximately equivalent angle measured in degrees. Syntax: public static double toDegrees(double angrad) Parameters: The parameter ‘angrad ‘represents an angle measured in...

2 minutes read.

Java Programming certification

The most common technology utilized in the creation of applications is Java. People and businesses like it because it turns original ideas into useful software solutions. A Java programming certification can...

6 minutes read.