VOOZH about

URL: https://www.geeksforgeeks.org/java/stringjoiner-class-in-java/

⇱ Java StringJoiner Class - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java StringJoiner Class

Last Updated : 23 Jul, 2025

StringJoiner class in Java provides an efficient way to concatenate multiple strings with a defined delimiter(character), optional prefix, and suffix. This class is especially useful when constructing formatted strings dynamically.

Example 1:


Output
Joined String: geeks, for, geeks

Explanation: In the above example, we have created a StringJoiner object with a comma and space as the delimiter. The toString() method is used to make the addition of string with the specified delimiter.

Example 2: Here, we will use the StringJoinerto join elements of an array of Strings.


Output
Geeks, for, Geeks

Key Features:

  • Delimiters: Define a separator between the strings.
  • Prefix and Suffix: Add optional characters before and after the final joined string.
  • Chaining: Easily chain calls to add elements for a clean and concise implementation.

Constructors of StringJoiner Class

1. StringJoiner(CharSequence delimiter): It creates a StringJoiner with a specified delimiter.

Syntax:

public StringJoiner(CharSequence delimiter)

2. StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix): It creates a StringJoiner with a delimiter, prefix, and suffix.

Syntax: 

public StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

Methods of StringJoiner Class

Method Action Performed
add()Adds a string to the StringJoiner.
length()Returns the length of the joined string.
merge()Merges the contents of another StringJoiner into the current one.
toString()Returns the final joined string.
setEmptyValue()Specifies a default value if no elements are added.

Example:


Output
StringJoiner with elements: geeks, for, geeks
Empty StringJoiner: No elements to join
StringJoiner with prefix and suffix: [geeks | for | geeks]
Length of joined string: 17
Comment