Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

StringJoiner — joining elements with a delimiter

StringJoiner builds text with a delimiter, prefix, and suffix. merge preserves the incoming content's internal delimiter.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

new StringJoiner(delimiter, prefix, suffix)
joiner.add(element)
joiner.merge(other)
joiner.toString()

java.util.StringJoiner joins elements. StringJoiner(CharSequence,CharSequence,CharSequence) takes delimiter, prefix, then suffix; it copies them and rejects null with NullPointerException.

add(CharSequence) copies an element; null becomes the text "null". Both add and merge return the receiving object for chaining.

merge(StringJoiner) appends nonempty content as one element, dropping its prefix and suffix but preserving its internal delimiter. An empty argument changes nothing; null causes NullPointerException.

toString() returns the framed text. Without elements, it returns prefix + suffix unless setEmptyValue overrides this. add("") makes the joiner nonempty.

Reference identifiers covered by this entry: StringJoiner.add, StringJoiner.merge, StringJoiner.toString.

Examples

import java.util.StringJoiner;

public class Main {
    public static void main(String[] args) {
        StringJoiner result = new StringJoiner(", ", "[", "]");
        System.out.println(result.toString());
        result.add("A");
        StringJoiner other = new StringJoiner("/", "(", ")");
        other.add("B").add("C");
        result.merge(other);
        System.out.println(result.toString());
    }
}

Result

[]
[A, B/C]

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources