Saturday, November 22, 2025
HomeLanguagesJavaStringJoiner toString() method in Java

StringJoiner toString() method in Java

The toString() of StringJoiner is used to convert StringJoiner to String. It returns the current value, consisting of the prefix, the values added so far separated by the delimiter, and the suffix, unless no elements have been added in which case, the prefix + suffix or the emptyValue characters are returned
Syntax: 

public String toString()

Returns: This method returns the string representation of this StringJoiner
Below programs illustrate the toString() method:
Example 1: To demonstrate toString() with delimiter ” ” 

Java




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


Output: 

StringJoiner: Geeks for Geeks

 

Example 2: To demonstrate toString() with delimiter “, “

Java




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


Output: 

StringJoiner: Geeks, for, Geeks, A, Computer, Portal

 

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32407 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6785 POSTS0 COMMENTS
Nicole Veronica
11932 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12000 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6864 POSTS0 COMMENTS
Umr Jansen
6852 POSTS0 COMMENTS