Java StringJoiner - setEmptyValue() Method
The java.util.StringJoiner.setEmptyValue() method is used to set the sequence of characters to be used when determining the string representation of this StringJoiner and no elements have been added yet, that is, when it is empty. A copy of the emptyValue parameter is made for this purpose. Note that once an add method has been called, the StringJoiner is no longer considered empty, even if the element(s) added correspond to the empty String.
Syntax
public StringJoiner setEmptyValue(CharSequence emptyValue)
Parameters
emptyValue |
Specify the characters to return as the value of an empty StringJoiner. |
Return Value
Returns this StringJoiner itself so the calls may be chained.
Exception
Throws NullPointerException, when the emptyValue parameter is null.
Example:
The example below shows how to use java.util.StringJoiner.setEmptyValue() method.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a StringJoiner object StringJoiner joinNames = new StringJoiner(", ", "[", "]"); //setting default empty value joinNames.setEmptyValue("It is empty."); //printing joinNames System.out.println("joinNames contains: " + joinNames); //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: It is empty. joinNames contains: [John, Marry, Kim]
❮ Java.util - StringJoiner