Java Utility Library

Java StringJoiner - add() Method



The java.util.StringJoiner.add() method is used to add a copy of the given CharSequence value as the next element of the StringJoiner value. If newElement is null, then "null" is added.

Syntax

public StringJoiner add(CharSequence newElement)

Parameters

newElement Specify the element to add.

Return Value

Returns a reference to this StringJoiner.

Exception

NA

Example:

In the example below, the java.util.StringJoiner.add() method is used to add character sequences separated by comma , in the given StringJoiner.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a StringJoiner object
    StringJoiner joinNames = new StringJoiner(", ");
   
    //Adding values to joinNames
    joinNames.add("John");
    joinNames.add("Marry");
    joinNames.add("Kim");
    joinNames.add("Jo");
    joinNames.add("Ramesh");

    //printing joinNames 
    System.out.println("joinNames contains: " + joinNames);
  }
}

The output of the above code will be:

joinNames contains: John, Marry, Kim, Jo, Ramesh

Example:Adding prefix and suffix

The example below shows how to add prefix and suffix in the given StringJoiner.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a StringJoiner object
    StringJoiner joinNames = new StringJoiner(", ","[","]");
   
    //Adding values to joinNames
    joinNames.add("John");
    joinNames.add("Marry");
    joinNames.add("Kim");

    //printing joinNames 
    System.out.println("joinNames contains: " + joinNames);
  }
}

The output of the above code will be:

joinNames contains: [John, Marry, Kim]

❮ Java.util - StringJoiner