Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a String?
3.
Concatenating Strings
4.
+ operator
4.1.
Example 1
4.2.
Example 2
5.
concat() method
5.1.
Syntax
5.2.
Example
6.
append() method
6.1.
Syntax
6.2.
Example
7.
format() method
7.1.
Syntax
7.2.
Example
8.
join() method
8.1.
Syntax
8.2.
Example
9.
add() method
9.1.
Example
10.
Collectors.joining() method
10.1.
Example
11.
Frequently Asked Questions
11.1.
What is StringJoiner?
11.2.
What is StringBuffer?
11.3.
What is Collectors Class?
12.
Conclusion
Last Updated: Mar 27, 2024
Easy

String Concatenation

Author Nagendra
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Java is one of the most popular programming languages. Learning Java reinforces essential computer science principles while also providing access to a wide range of professional options.
A string is a collection of characters in Java, while a char is a single number used to hold variables. By implementing strings as built-in objects, Java can provide a full set of features that facilitate string manipulation. It offers, among other things, techniques for comparing two strings, searching for a substring, and concatenating two strings. This blog discusses the different approaches used for string concatenation.

Without further ado, let's get started.

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

public class String_Conacatenation {
   public static void main(String args[]) {
      String s = "String";
      s = s + " Concatenation";
      System.out.println(s);
   }
}

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Concatenating Strings

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.

+ 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

public class String_Conacatenation {
   public static void main(String args[]) {
      String s = "String";
      s = s + " Concatenation";
      System.out.println(s);
   }
}

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

public class String_Conacatenation {
   public static void main(String args[]) {
    String s=10+80+"String"+40+40;  
    System.out.println(s);
   }
}

Output

90String4040

Explanation

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

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

public class String_Conacatenation 
{
   public static void main(String args[]) 
   {
      String s = "String";
      String s1 =" Concatenation";
      System.out.println(s.concat(s1));
   }
}

Output

String Concatenation

Explanation

The concat() method concatenates the first String with the second 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

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));
   }
}

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.

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

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);
   }
}

Output

String Concatenation

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.

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

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);
   }
}

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.

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

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);
   }
}

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

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
   }
}

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.

Frequently Asked Questions

What is StringJoiner?

StringJoiner is a class in java.util package which is used to create a string of characters separated by a delimiter, starting with a supplied prefix and finishing with a given suffix.

What is StringBuffer?

StringBuffer is a String companion class that provides a lot of the same functionality as strings.

What is Collectors Class?

Collectors are the last class in the hierarchy, and it extends the Object class. It allows you to perform reduction operations such as grouping data into collections, summarising materials based on various criteria, and so on.

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 Coding Ninjas Studio 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 -

Do upvote our blog to help other ninjas grow. 

Happy Coding!!

Previous article
String Comparison
Next article
String Class Methods
Live masterclass