0% found this document useful (0 votes)
16 views8 pages

Skip To Contente

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views8 pages

Skip To Contente

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 8

Skip to content

geeksforgeeks
Courses 90% Refund
Tutorials
Java
Practice
Contests

Sign In

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

Content Improvement Event


Share Your Experiences
Java Tutorial
Overview of Java
Basics of Java
Input/Output in Java
Flow Control in Java
Operators in Java
Strings in Java
Strings in Java
String class in Java
Java.lang.String class in Java | Set 2
Why Java Strings are Immutable?
StringBuffer class in Java
StringBuilder Class in Java with Examples
String vs StringBuilder vs StringBuffer in Java
StringTokenizer Class in Java
StringTokenizer Methods in Java with Examples | Set 2
StringJoiner Class in Java
Arrays in Java
OOPS in Java
Inheritance in Java
Abstraction in Java
Encapsulation in Java
Polymorphism in Java
Constructors in Java
Methods in Java
Interfaces in Java
Wrapper Classes in Java
Keywords in Java
Access Modifiers in Java
Memory Allocation in Java
Classes of Java
Packages in Java
Java Collection Tutorial
Exception Handling in Java
Multithreading in Java
Synchronization in Java
File Handling in Java
Java Regex
Java IO
Java Networking
JDBC - Java Database Connectivity
Java 8 Features - Complete Tutorial
Java Backend DevelopmentCourse
StringJoiner Class in Java
Last Updated : 24 Jan, 2022
StringJoiner is a class in java.util package is used to construct a sequence of
characters(strings) separated by a delimiter and optionally starting with a
supplied prefix and ending with a given suffix. Though this can also be done with
the help of the StringBuilder class to append delimiter after each string,
StringJoiner provides an easy way to do that without much code to write.

Constructors of StringJoiner Class


1. StringJoiner(CharSequence delimiter): It constructs a StringJoiner with no
characters, no prefix or suffix, and a copy of the supplied delimiter.

Syntax:

public StringJoiner(CharSequence delimiter)


Parameters: The sequence of characters to be used between each element added to the
StringJoiner value

Exception Thrown: NullPointerException if the delimiter is null

2. StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix):


It constructs a StringJoiner with no characters using copies of the supplied
prefix, delimiter, and suffix. If no characters are added to the StringJoiner and
methods accessing the string value are invoked, it will return the prefix + suffix
(or properties thereof) in the result unless setEmptyValue has first been called.

Syntax:

public StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence


suffix)
Parameters:

The sequence of characters to be used between each element added to the


StringJoiner value
The sequence of characters to be used at the beginning
The sequence of characters to be used at the end
Exception Thrown: NullPointerException if prefix, delimiter, or suffix is null.

Methods of StringJoiner Class


Method Action Performed
add() Adds a copy of the given CharSequence value as the next element of the
StringJoiner value. If newElement is null, then “null” is added.
length() Returns the length of the String representation of this StringJoiner.
merge() Adds the contents of the given StringJoiner without prefix and suffix
as the next element if it is non-empty. If the given StringJoiner is empty, the
call has no effect. Suppose the other StringJoiner is using a different delimiter.
In that case, elements from the other StringJoiner are concatenated with that
delimiter, and the result is appended to this StringJoiner as a single element.
toString() Returns the String object of this StringJoiner
setEmptyValue() Sets the string to be used when determining the string
representation of this StringJoiner, and no elements have been added yet; that is
when it is empty
Example:

// Java program to Demonstrate Methods


// of StringJoiner class

// Importing required classes


import java.util.ArrayList;
import java.util.StringJoiner;

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating an empty ArrayList of string type
ArrayList<String> al = new ArrayList<>();

// Adding elements to above List


al.add("Ram");
al.add("Shyam");
al.add("Alice");
al.add("Bob");

// Creating object of class inside main()


StringJoiner sj1 = new StringJoiner(",");

// Using setEmptyValue() method


sj1.setEmptyValue("sj1 is empty");
System.out.println(sj1);

// Using add() method


sj1.add(al.get(0)).add(al.get(1));
System.out.println(sj1);

// Using length() method


System.out.println("Length of sj1 : "
+ sj1.length());

StringJoiner sj2 = new StringJoiner(":");


sj2.add(al.get(2)).add(al.get(3));

// Using merge() method


sj1.merge(sj2);

// Using toString() method


System.out.println(sj1.toString());

System.out.println("Length of new sj1 : "


+ sj1.length());
}
}
Output
sj1 is empty
Ram,Shyam
Length of sj1 : 9
Ram,Shyam,Alice:Bob
Length of new sj1 : 19

Three 90 Challenge is back on popular demand! After processing refunds worth INR
1CR+, we are back with the offer if you missed it the first time. Get 90% course
fee refund in 90 days. Avail now!
Want to be a master in Backend Development with Java for building robust and
scalable applications? Enroll in Java Backend and Development Live Course by
GeeksforGeeks to get your hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration, and more through hands-on
experiences and live projects. Are you new to Backend development or want to be a
Java Pro? This course equips you with all you need for building high-performance,
heavy-loaded backend systems in Java. Ready to take your Java Backend skills to the
next level? Enroll now and take your development career to sky highs.

Gaurav Miglani

40
Previous Article
StringTokenizer Methods in Java with Examples | Set 2
Next Article
Arrays in Java
Read More
Down Arrow
Similar Reads
StringJoiner Class vs String.join() Method to Join String in Java with Examples
Prior to Java 8 when we need to concatenate a group of strings we need to write
that code manually in addition to this we needed to repeatedly use delimiter and
sometimes it leads to several mistakes but after Java 8 we can concatenate the
strings using StringJoiner class and String.join() method then we can easily
achieve our goal. Example: Withou
6 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 newElement which is the element
to be added.Returns: This
1 min read
StringJoiner length() method in Java
The length() of StringJoiner is used to find out the length of the StringJoiner in
characters. It returns the length of the String representation of this
StringJoiner. Note that if no add methods have been called, then the length of the
String representation (either prefix + suffix or emptyValue) will be returned. The
value should be equivalent to
2 min read
StringJoiner merge() method in Java
The merge(StringJoiner other) of StringJoiner adds the contents of the given
StringJoiner without prefix and suffix as the next element if it is non-empty. If
the given StringJoiner is empty, the call has no effect.Syntax: public StringJoiner
merge(StringJoiner other) Parameters: This method accepts a mandatory parameter
other which is the StringJo
3 min read
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 returnedSyntax:
public String toString() Returns:
2 min read
StringJoiner setEmptyValue() method in Java
The setEmptyValue(CharSequence emptyValue) of StringJoiner sets the sequence of
characters to be used when determining the string representation of this
StringJoiner and no elements have been added yet, that is, when it is empty. A copy
of the emptyValue parameter is made for this purpose. Note that once an add method
has been called, the StringJoi
2 min read
When to use StringJoiner over StringBuilder?
Prerequisite: StringJoinerStringJoiner is very useful, when you need to join
Strings in a Stream. Task : Suppose we want the string "[George:Sally:Fred]", where
we have given a string array that contains "George", "Sally" and
"Fred".StringJoiner provide add(String str) method to concatenate the strings based
on supplied delimiter,prefix and suffix
2 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class
Class represent classes and interfaces in a running Java application. The primitive
Java types (boolean, byte, char, short, int, long, float, and double), and the
keyword void are also represented as Class objects. It has no public constructor.
Class objects are cons
15+ min read
Java.lang.Class class in Java | Set 2
Java.lang.Class class in Java | Set 1 More methods: 1. int getModifiers() : This
method returns the Java language modifiers for this class or interface, encoded in
an integer. The modifiers consist of the Java Virtual Machine's constants for
public, protected, private, final, static, abstract and interface. These modifiers
are already decoded in Mo
15+ min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and
java.sql.Date in many instances. Whenever the java application interacts with the
database, we should use these instead of java.util.Date. The reason is JDBC i.e.
java database connectivity uses these to identify SQL Date and Timestamp. Here let
us see the differences
7 min read
Article Tags :
Java
Java - util package
Java-StringJoiner
Practice Tags :
Java
three90RightbarBannerImg

course-img
216k+ interested Geeks
Java Programming Online Course [Complete Beginner to Advanced]
Avail 90% Refund
course-img
30k+ interested Geeks
Manual to Automation Testing: A QA Engineer's Guide
Avail 90% Refund
course-img
217k+ interested Geeks
JAVA Backend Development - Live
Avail 90% Refund

geeksforgeeks-footer-logo
Corporate & Communications Address:- A-143, 9th 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
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS
Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
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
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Economics
Management
HR Management
Finance
Income Tax
Databases
SQL
MYSQL
PostgreSQL
PL/SQL
MongoDB
Preparation Corner
Company-Wise Recruitment Process
Resume Templates
Aptitude Preparation
Puzzles
Company-Wise Preparation
Companies
Colleges
Competitive Exams
JEE Advanced
UGC NET
UPSC
SSC CGL
SBI PO
SBI Clerk
IBPS PO
IBPS Clerk
More Tutorials
Software Development
Software Testing
Product Management
Project Management
Linux
Excel
All Cheat Sheets
Recent Articles
Free Online Tools
Typing Test
Image Editor
Code Formatters
Code Converters
Currency Converter
Random Number Generator
Random Password Generator
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@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
Got It !
Lightbox

You might also like