Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java StringBuilder Class
Next article icon

Java StringJoiner Class

Last Updated : 10 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Java
// Demonstration of StringJoiner Class  import java.util.StringJoiner;  public class Geeks{     public static void main(String[] args) {                // Create a StringJoiner with a delimiter         StringJoiner sj = new StringJoiner(", ");          // Add strings which you need to join         sj.add("geeks").add("for").add("geeks");          System.out.println("Joined String: " + sj.toString());     } } 

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 StringJoiner to join elements of an array of Strings.

Java
// Using StringJoiner with Array of Strings import java.util.StringJoiner;  public class Geeks {     public static void main(String[] args) {         String[] s1 = {"Geeks", "for", "Geeks"};          // Create StringJoiner with a delimiter         StringJoiner sj = new StringJoiner(", ");          // Adding array elements to StringJoiner         for (String s2 : s1) {             sj.add(s2);         }          System.out.println(sj.toString());     } } 

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:

Java
// Demostrating different methods  // of StringJoiner Class import java.util.StringJoiner;  public class Geeks {     public static void main(String[] args) {                  // add() method         StringJoiner sj1 = new StringJoiner(", ");         sj1.add("geeks").add("for").add("geeks");         System.out.println("StringJoiner with elements: " + sj1.toString());                  // setEmptyValue() method          StringJoiner sj2 = new StringJoiner(", ");         sj2.setEmptyValue("No elements to join");         System.out.println("Empty StringJoiner: " + sj2.toString());                    // toString() method         StringJoiner sj3 = new StringJoiner(" | ", "[", "]");         sj3.add("geeks").add("for").add("geeks");         System.out.println("StringJoiner with prefix and suffix: " + sj3.toString());                  // Checking the length of the joined string         StringJoiner sj4 = new StringJoiner(", ");         sj4.add("geeks").add("for").add("geeks");         System.out.println("Length of joined string: " + sj4.length());              } } 

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 

Next Article
Java StringBuilder Class

G

Gaurav Miglani
Improve
Article Tags :
  • Java
  • Java - util package
  • Java-StringJoiner
Practice Tags :
  • Java

Similar Reads

  • Java StringBuilder Class
    In Java, the StringBuilder class is a part of the java.lang package that provides a mutable sequence of characters. Unlike String (which is immutable), StringBuilder allows in-place modifications, making it memory-efficient and faster for frequent string operations. Declaration: StringBuilder sb = n
    7 min read
  • Java Writer Class
    Java writer class is an abstract class in the java.io package. It is designed for writing character streams. Writer class in Java provides methods for writing characters, arrays of characters, and strings. Since it is an abstract class, we cannot create an instance of it directly. Instead, we will u
    5 min read
  • Joiner class | Guava | Java
    Guava's Joiner class provides various methods to handle joining operations on string, objects, etc. This class provides advanced functionality for the join operation. Declaration: Following is the declaration for com.google.common.base.Joiner class : @GwtCompatible public class Joiner extends Object
    2 min read
  • StringJoiner add() method in Java
    The add(CharSequence newElement) of StringJoiner adds a copy of the given CharSequence value as the next element of the StringJoiner value. If newElement is null, then "null" is added.Syntax: public StringJoiner add(CharSequence newElement) Parameters: This method takes a mandatory parameter newElem
    1 min read
  • Java Thread Class
    Thread is a line of execution within a program. Each program can have multiple associated threads. Each thread has a priority which is used by the thread scheduler to determine which thread must run first. Java provides a thread class that has various method calls to manage the behavior of threads b
    5 min read
  • Java Reader Class
    Reader class in Java is an abstract class used for reading character streams. It serves as the base class for various subclasses like FileReader, BufferedReader, CharArrayReader, and others, which provide more efficient implementations of the read() method. To work with the Reader class, we must ext
    7 min read
  • Java Pattern Class
    The Pattern class in Java is used for defining regular expressions (regex) to perform pattern matching on strings. It is part of the java.util.regex package and it plays a key role in searching, replacing, and manipulating strings based on patterns. The Matcher class works together with Pattern to p
    3 min read
  • Static class in Java
    Java allows a class to be defined within another class. These are called Nested Classes. Classes can be static which most developers are aware of, henceforth some classes can be made static in Java. Java supports Static Instance Variables, Static Methods, Static Block, and Static Classes. The class
    3 min read
  • Matcher Class in Java
    In Java, Matcher is a class that is implemented by the MatchResult interface, that performs match operations on a character sequence by interpreting a Pattern. Below, we can see the declaration of java.util.regex.Matcher in java.lang.Object Class: public final class Matcher extends Object implements
    4 min read
  • Java Observable Class
    In Java, the Observable class is used to create objects that can be observed by other parts of the program. When an object of such a subclass undergoes a change, observing classes are notified. The update() method is called when an observer is notified of a change. Note: The Observable class and Obs
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences