String Concatenation In Java

In Java programming, String concatenation is a fundamental operation in Java. It is essential for manipulating and combining text data. Java provides multiple ways to concatenate strings, each with its advantages and use cases. In this section, we will discuss the various methods of string concatenation in Java.

  • Using "+" (String concatenation) Operator
  • Using String.concat Method
  • Using the StringBuilder or StringBuffer Class
  • Using String.join Method
  • Using Java String.format Method
  • Using Collector.joining Method
  • 1. Using the + Operator

One of the most straightforward and widely utilized approaches to combine strings in Java involves the use of the + operator. By placing the + operator between two or more strings, we can easily concatenate them. For instance:

TestStringConcatenation1.java

Example

class TestStringConcatenation1{

 public static void main(String args[]){

   String s="Sachin"+" Tendulkar";

   System.out.println(s);//Sachin Tendulkar

 }

}

Output:

Output

Sachin Tendulkar

The string in Java is internally manipulated by the Java compiler using the statement presented below.

Example

String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();

Java utilizes the StringBuilder (or StringBuffer) class along with its append method to execute String concatenation. By using the concatenation operator, a new String is generated by adding the second operand to the conclusion of the first operand. This operator is capable of concatenating both Strings and primitive values. To grasp this concept better, let's explore a Java program.

TestStringConcatenation2.java

Example

class TestStringConcatenation2{

 public static void main(String args[]){

   String s=50+30+"Sachin"+40+40;

   System.out.println(s);//80Sachin4040

 }

}

Output:

Output

80Sachin4040

Note: After a string literal, all the + will be treated as string concatenation operator.

2. Using the String.concat Method

The concat function is a member of the Java String class that serves as a substitute for the + operator when combining strings. Its purpose is to add one string at the end of another.

Synatx:

Example

public String concat(String another)

Let's see the example of String.concat method.

TestStringConcatenation3.java

Example

class TestStringConcatenation3{

 public static void main(String args[]){

   String s1="Sachin ";

   String s2="Tendulkar";

   String s3=s1.concat(s2);

   System.out.println(s3);//Sachin Tendulkar

  }

}

Output:

Output

Sachin Tendulkar

In the Java program above, the concatenation of two String objects, s1 and s2, is achieved by utilizing the concat method. The resulting concatenation is then stored in the s3 object.

3. Using Java StringBuilder or StringBuffer Class

In order to tackle the performance issues related to the + operator and concat method, Java offers two dedicated classes, StringBuilder and StringBuffer, which are tailored for effective manipulation of strings.

The StringBuilder class offers the append method for combining strings. This method can take various types of arguments such as Objects, StringBuilder, int, char, CharSequence, boolean, float, and double. In Java, StringBuilder is widely used and known for its efficiency in string concatenation. It is a mutable class, allowing modifications and updates to the values stored within its objects.

StringBuilderExample.java

Example

public class StringBuilderExample {

    public static void main(String[] args) {

        String firstName = "Manoj";

        String lastName = "Mamilla";

        // Using StringBuilder for efficient string concatenation

        StringBuilder stringBuilder = new StringBuilder();

        stringBuilder.append("Hello, ");

        stringBuilder.append(firstName);

        stringBuilder.append(" ");

        stringBuilder.append(lastName);

        String result = stringBuilder.toString();

        System.out.println(result);  

    }

}

Output:

Output

Hello, Manoj Mamilla

The classes StringBuilder and StringBuffer are both mutable, allowing modifications without the need to create new instances for each operation. This characteristic enhances their efficiency compared to using the + operator or concat method, particularly in situations where there is frequent concatenation within loops.

4. Using String.join Method

The String.join method was introduced in Java 8 as a succinct and clear approach to merging multiple strings using a specified delimiter:

StringJoinExample.java

Example

public class StringJoinExample {

    public static void main(String[] args) {

        String firstName = "Manoj";

        String lastName = "Mamilla";

        // Using String.join for concatenation with a delimiter

        String result = String.join(" ", "Hello,", firstName, lastName);

        System.out.println(result);  

    }

}

Output:

Output

Hello, Manoj Mamilla

There exist alternative methods for combining Strings in Java.

5. Using the String.format Method

The String.format function in Java offers an alternative method for string concatenation with additional flexibility in formatting. Below is a demonstration utilizing the format function.

StringFormatExample.java

Example

public class StringFormatExample {

    public static void main(String[] args) {

        String firstName = "Manoj";

        String lastName = "Mamilla";

        // Using String.format for string concatenation with formatting

        String result = String.format("Hello, %s %s", firstName, lastName);

        System.out.println(result);  

    }

}

Output:

Output

Hello, Manoj Mamilla

In this scenario, the outcome of String objects is designated as the merged outcome of Strings firstName and lastName utilizing the String.format function. format requires inputs in the form of a format specifier, succeeded by String objects or values.

6. Using Collectors.joining Method (Java 8 and above versions)

In Java 8, the Collectors class provides the joining method, which merges the input elements in the order they are encountered.

ColJoining.java

Example

import java.util.*;

import java.util.stream.Collectors;

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:

Output

abc, pqr, xyz

Conclusion

In Java, string concatenation is a frequently used operation, and the selection of the appropriate technique relies on the particular needs and performance factors. Although the + operator and concat function are straightforward and handy, they might not be the optimal choice for extensive operations.

In scenarios like these, it is advisable to utilize StringBuilder or StringBuffer for improved efficiency. Furthermore, the String.join method offers a neat and succinct approach to merging strings using a defined delimiter. Having a grasp of the advantages and limitations of each technique empowers Java programmers to make well-informed choices depending on their application's requirements.

String Concatenation in Java MCQ

  1. Which of the following methods should be used for efficient string concatenation in Java when dealing with multiple concatenations?
  • Using the + operator
  • Using the concat method
  • Using the StringBuilder or StringBuffer classes
  • Using the String.join method

Explanation: StringBuilder and StringBuffer classes are more efficient for multiple concatenations due to their mutable nature.

  1. What is the time complexity of concatenating two strings using the + operator in Java?
  • O(n)
  • O(log n)
  • O(n^2)
  • O(1)

Explanation: Concatenating two strings using the + operator in a loop results in a time complexity of O(n^2), where n is the total number of characters.

  1. Which of the following statements is true regarding the immutability of strings in Java?
  • Strings in Java are mutable and can be modified after creation.
  • Strings in Java are immutable and cannot be modified after creation.
  • Strings in Java can be made mutable by using the mutable keyword.
  • Immutability of strings depends on the Java version being used.

Explanation: Strings in Java are immutable, meaning their values cannot be changed once they are created.

  1. Which method concatenates multiple strings efficiently in Java 8 and later versions?
  • String.concat
  • StringBuilder.append
  • String.join
  • StringBuffer.append

Explanation: In Java 8 and later versions, the String.join method efficiently concatenates multiple strings using a delimiter.

  1. What is the benefit of using StringBuilder over string concatenation using the + operator?
  • StringBuilder provides better readability.
  • StringBuilder is faster and more memory-efficient for multiple concatenations.
  • StringBuilder ensures thread safety.
  • StringBuilder allows concatenation of different data types.

Explanation: The StringBuilder class is mutable, making it more efficient than using the + operator for multiple concatenations. This is due to the fact that StringBuilder does not generate new string objects for each concatenation operation.

Input Required

This code uses input(). Please provide values below: