How to Join Strings

JavaJavaBeginner
Practice Now

Introduction

In Java, it is sometimes necessary to join two or more strings into a single string. This can be done easily using the join() method of the String class. The join() method takes a delimiter as its first argument and returns a single string after joining all the given strings.

Create Strings to Join

We will create some strings to join using the join() method. In the main function, create three strings str1, str2, and str3, which will be joined together.

public class JoinStrings {
    public static void main(String[] args) {
        String str1 = "Mango";
        String str2 = "Orange";
        String str3 = "Apple";
    }
}

Join Strings using join() method

Now, we will use the join() method to join the strings. In the main() function, add the following code:

String str = String.join("-", str1, str2, str3);
System.out.println(str);

Here, we are joining the three strings str1, str2, and str3 with a hyphen (-) separator.

Join List of Strings

Instead of using separate arguments to join strings, we can join a list of strings as shown below:

List<String> list = Arrays.asList("Mango", "Orange", "Apple");
String str = String.join("-", list);
System.out.println(str);

Here, we are passing the list of strings to the join() method instead of providing them as separate arguments.

Using Stream to Join Strings

If you are using Java 8 or a higher version, you can use the stream() method of the list and then collect all the strings into a single string using the joining() method of the Collectors class.

List<String> list = Arrays.asList("Mango", "Orange", "Apple");
String str = list.stream().collect(Collectors.joining("-"));
System.out.println(str);

This will produce the same output as the previous examples.

Compile and Run the Code

Now, save the JoinStrings.java file and run it using the following commands in the terminal:

javac JoinStrings.java
java JoinStrings

You should see the output Mango-Orange-Apple on the terminal.

Summary

In this lab, we learned how to join strings using the join() method of the String class. We also covered different ways to join strings such as passing separate arguments, a list of strings, and using the stream method to join the strings. By following the steps outlined in this lab, you should now be able to join any number of strings into a single string using Java code.

Other Java Tutorials you may like