Builder: StringJoiner.setEmptyValue for an empty result

Without setEmptyValue, an empty StringJoiner still prints its prefix and suffix with nothing between them; setEmptyValue supplies a whole replacement string to use instead as long as add() has never been called. Once an element is added, the joiner switches back to its normal prefix/delimiter/suffix output.

Code
StringJoiner joiner = new StringJoiner(", ", "[", "]");
joiner.setEmptyValue("(none)");
System.out.println("Before adding: " + joiner);
joiner.add("first");
System.out.println("After adding: " + joiner);
Output
Before adding: (none)
After adding: [first]
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms