What is StringUtils.join() in Java?

Overview

join() 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 array/iterable/iterator/varargs into a single string containing the provided list of elements.

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 join(final Object[] array, final char delimiter, final int startIndex, final int endIndex)

Parameters

  • final Object[] array: The array of values to join.
  • final char delimiter: The delimiter character to use.
  • final int startIndex: The first index to start joining from.
  • final int endIndex: The last index to stop joining from (exclusive).

Return value

This method returns the joined string with the delimiter.

For the overloaded methods, refer here.

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"};
char sep = '-';
System.out.printf("StringUtils.join('%s', %s) = '%s'", Arrays.toString(strings), sep, StringUtils.join(strings, sep));
System.out.println();
// Example 2
strings = new String[]{"hello", null, "edpresso"};
sep = '-';
System.out.printf("StringUtils.join('%s', %s) = '%s'", Arrays.toString(strings), sep, StringUtils.join(strings, sep));
System.out.println();
}
}

Output

The output of the code will be as follows:

StringUtils.join('[hello, educative, edpresso]', -) = 'hello-educative-edpresso'
StringUtils.join('[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