Skip to content
Related Articles

Related Articles

StringJoiner add() method in Java
  • Difficulty Level : Basic
  • Last Updated : 12 Sep, 2018

The add(CharSequence newElement) of StringJoiner adds 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: This method takes a mandatory parameter newElement which is the element to be added.

Returns: This method returns a reference to this StringJoiner

Below programs illustrate the add() method:



Example 1: To demonstrate add() with delimeter ” ”




// Java program to demonstrate
// add() method of StringJoiner
  
import java.util.StringJoiner;
  
public class GFG1 {
    public static void main(String[] args)
    {
  
        // Creating StringJoiner with delimeter " "
        StringJoiner str = new StringJoiner(" ");
  
        // Adding elements in the StringJoiner
        str.add("Geeks");
        str.add("for");
        str.add("Geeks");
  
        // Print the StringJoiner
        System.out.println(str.toString());
    }
}
Output:
Geeks for Geeks

Example 2: To demonstrate add() with delimeter “,”




// Java program to demonstrate
// add() method of StringJoiner
  
import java.util.StringJoiner;
  
public class GFG1 {
    public static void main(String[] args)
    {
  
        // Creating StringJoiner with delimeter ","
        StringJoiner str = new StringJoiner(",");
  
        // Adding elements in the StringJoiner
        str.add("Geeks");
        str.add("for");
        str.add("Geeks");
  
        // Print the StringJoiner
        System.out.println(str.toString());
    }
}
Output:
Geeks,for,Geeks

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :