Java String join()

Filed Under: Java

Java String join() function is used to join multiple strings to create a new string with the specified delimiter.

Java String join()

Java String join() method is added in Java 8 release. There are two variants of join() method, both of them are static methods.


public static String join(CharSequence delimiter, CharSequence... elements)

public static String join(CharSequence delimiter,
            Iterable<? extends CharSequence> elements)

The first argument is the delimiter string to use when joining the strings. CharSequence is an interface and some well known implementations are String, StringBuffer and StringBuilder.

Let’s look at these methods with some example.


String msg1 = String.join(",", "A", "B", new StringBuilder("C"), new StringBuffer("D"));
System.out.println(msg1);

Output: A,B,C,D

Notice that I have used StringBuffer and StringBuilder as elements to join since they implement CharSequence interface.

Let’s look at an example where we will pass an Iterable whose elements will be joined with the given delimiter.


List<String> words = Arrays.asList(new String[] { "Hello", "World", "2019" });
String msg = String.join(" ", words);
System.out.println(msg);

Output: Hello World 2019

We can execute above code snippets using jshell terminal too.

Java String join() with delimiter

Java String join() Example – jshell

You can checkout more String examples from our GitHub Repository.

Reference: API Doc

Comments

  1. Santhosh says:

    I am cse engineering student 1st year

  2. sadiqullah says:

    thank’s so about this artical

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages