How to Concatenate Multiple Strings in Java?
Last Updated :
02 Feb, 2024
In Java programming, there are a lot of ways to concatenate multiple strings. For this, we have taken three or more String values then we concatenate those String values by using different ways.
In this article, we have used two different ways, we will explain each method with one example for a better understanding of the concept.
Methods to Concatenate Multiple Strings
Here, we have used these two different ways to concatenate multiple Strings in Java rather than using the basic concat() method. Every way provides a unique solution for this problem. Now we will explain each method with examples in Java.
Program to Concatenate Multiple Strings in Java
Below are the implementations of the two methods:
Method 1: StringBuilder
This is an approach for concatenating multiple Strings in Java, This StringBuilder class provides one method which is append() method. This method is used to append the string values and then take the result into one String value.
Java
import java.util.*;
public class ConcatenationExample {
public static void main(String[] args) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append( " Welcome " );
stringBuilder.append( " To " );
stringBuilder.append( " GeeksforGeeks " );
String result = stringBuilder.toString();
System.out.println(result);
}
}
|
Output
Welcome To GeeksforGeeks
Explanation of the above Program:
- This Java program demonstrates string concatenation using
StringBuilder
.
- It creates a
StringBuilder
named stringBuilder.
- At last, it combines words into a sentence using
toString()
and prints the result.
Method 2: StringJoiner
This is another approach for concatenate multiple Strings in Java. For this, we have used StringJoiner class in Java. After that we have created object for this StringJoiner class After that we have converted the result into String value.
Java
import java.util.StringJoiner;
public class ConcatenationExample {
public static void main(String[] args) {
StringJoiner stringJoiner = new StringJoiner( " " );
stringJoiner.add( " Welcome " );
stringJoiner.add( " To " );
stringJoiner.add( " GeeksforGeeks " );
String result = stringJoiner.toString();
System.out.println(result);
}
}
|
Output
Welcome To GeeksforGeeks
Explanation of the above Program:
- This Java program demonstrates string concatenation using the
StringJoiner
class.
- It creates a
StringJoiner
named stringJoiner
with a space.
- It combines separate words into a single sentence using
toString()
and prints the result.
Share your thoughts in the comments
Please Login to comment...