What is StringUtils.joinWith() in Java?

Overview

joinWith() is a staticThe methods in Java that can be called without creating an object of the class. method of the StringUtils class that is used to join the elements of the provided varargs into a single string containing the provided elements with a separator.

How to import StringUtils

The definition of StringUtils can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:

<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
</dependency>

For other versions of the commons-lang package, refer to the Maven Repository.

You can import the StringUtils class as follows:

import org.apache.commons.lang3.StringUtils;

Syntax

public static String joinWith(final String delimiter, final Object... array)

Parameters

  • final String delimiter: The separator character to use.
  • final Object... array: The varargs to join together.

Return value

This method returns the joined string.

Code

import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
public class Main{
public static void main(String[] args) {
// Example 1
String[] strings = {"hello", "educative", "edpresso"};
String sep = ";";
System.out.printf("StringUtils.joinWith('%s', %s) = '%s'", Arrays.toString(strings), sep, StringUtils.joinWith(sep, strings));
System.out.println();
// Example 2
strings = new String[]{"hello", null, "edpresso"};
sep = ";";
System.out.printf("StringUtils.joinWith('%s', %s) = '%s'", Arrays.toString(strings), sep, StringUtils.joinWith(sep, strings));
System.out.println();
}
}

Output

The output of the code will be as follows:

StringUtils.joinWith('[hello, educative, edpresso]', ;) = 'hello;educative;edpresso'
StringUtils.joinWith('[hello, null, edpresso]', ;) = 'hello;;edpresso'

Example 1

  • strings = ["hello", "educative", "edpresso"]
  • separator = ";"

The method returns hello;educative;edpresso, joining all the elements with ; as the separator.

Example 2

  • strings = ["hello", null, "edpresso"]
  • separator = ";"

The method returns hello;;edpresso. null elements are treated as empty strings.

Free Resources

Attributions:
  1. undefined by undefined
  2. undefined by undefined