Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. Java
  4. Complete Guide to String Joiner in Java with Examples

Complete Guide to String Joiner in Java with Examples

Date- Jul 13,2023 Updated Jan 2026 3753
java string joiner

Overview of String Joiner

The StringJoiner class was introduced in Java 8 as part of the java.util package. It provides a flexible and efficient way to concatenate strings, especially when dealing with collections or loops. Unlike traditional string concatenation using the + operator, which can lead to performance issues due to the creation of multiple intermediate string objects, StringJoiner offers a more memory-efficient solution by allowing you to build a single string incrementally.

One of the most significant advantages of using StringJoiner is its ability to define a delimiter, as well as optional prefix and suffix strings. This makes it ideal for producing formatted output, such as CSV files or JSON strings, where specific formatting is essential.

Creating a StringJoiner

To create a StringJoiner object, you need to specify the delimiter, as well as optional prefix and suffix strings. The constructor takes three parameters: the delimiter, the prefix, and the suffix.

StringJoiner joiner = new StringJoiner(", ", "[", "]");

In this example, the delimiter is set to ", ", the prefix is "[", and the suffix is "]". You can customize these values based on your specific requirements, allowing for versatile string formatting.

Adding Elements

Once you have created a StringJoiner object, you can add elements to it using the add method. This method can be called multiple times to append various strings.

StringJoiner joiner1 = new StringJoiner(", ");
joiner1.add("Apple");
joiner1.add("Banana");
joiner1.add("Orange");
String result1 = joiner1.toString();
System.out.println(result1);

The resulting string will be "Apple, Banana, Orange". This demonstrates how easily you can build a string by adding elements incrementally.

Merging StringJoiners

Another useful feature of the StringJoiner class is the ability to merge multiple StringJoiner objects using the merge method. This can be particularly handy when you want to combine separate groups of elements into a single string.

StringJoiner fruitsJoiner = new StringJoiner(", ");
fruitsJoiner.add("Apple");
fruitsJoiner.add("Banana");
StringJoiner colorsJoiner = new StringJoiner(", ");
colorsJoiner.add("Red");
colorsJoiner.add("Green");
fruitsJoiner.merge(colorsJoiner);
String result2 = fruitsJoiner.toString();
System.out.println(result2);

In this example, the output will be "Apple, Banana, Red, Green", effectively combining the contents of both joiners.

Handling Empty Joiners

If you have an empty StringJoiner and no elements are added to it, the resulting string will also be empty. However, you can specify a default value to handle such cases by providing a prefix and suffix.

StringJoiner joiner2 = new StringJoiner(", ", "Prefix: ", " Suffix");
String result3 = joiner2.toString();
System.out.println(result3);

In this case, if no elements are added, the resulting string will be "Prefix: Suffix". This is particularly useful for generating output that needs to maintain a specific format even when no data is present.

Real-World Use Cases

The StringJoiner class can be applied in various real-world scenarios. For example, when generating a CSV (Comma-Separated Values) output, you can use StringJoiner to concatenate values from a data structure seamlessly.

StringJoiner csvJoiner = new StringJoiner(",");
csvJoiner.add("John");
csvJoiner.add("Doe");
csvJoiner.add("30");
String csvOutput = csvJoiner.toString();
System.out.println(csvOutput);

This code outputs: "John,Doe,30", which can then be used for file writing or data transmission.

Edge Cases & Gotchas

When working with StringJoiner, there are a few edge cases and gotchas to keep in mind:

  • Empty Joiners: As mentioned earlier, if you create a StringJoiner and do not add any elements, the output will be the prefix and suffix only. Be cautious when using it in scenarios where data might be absent.
  • Null Elements: If you attempt to add null elements, they are treated as the string "null". This can lead to unexpected results if not handled properly.
  • Thread Safety: StringJoiner is not synchronized. If you are using it in a multi-threaded environment, consider using synchronization mechanisms to prevent data inconsistency.

Performance & Best Practices

When it comes to performance, StringJoiner is generally more efficient than using traditional string concatenation methods, particularly in scenarios involving loops.

Best Practices:

  • Use StringJoiner for Concatenation: When you need to concatenate multiple strings, especially in loops or collections, prefer StringJoiner over the + operator.
  • Specify Prefix and Suffix: Always specify a prefix and suffix when you expect to have no elements in your joiner. This ensures that your output maintains a consistent format.
  • Handle Null Values: Implement checks for null values before adding elements to avoid unexpected string results.

Conclusion

The StringJoiner class is a powerful tool for string manipulation in Java. It simplifies the process of concatenating strings with specified delimiters, prefixes, and suffixes, enhancing code readability and maintainability.

  • Utilize StringJoiner for efficient string concatenation.
  • Take advantage of merging capabilities to combine multiple string groups.
  • Be mindful of edge cases, such as empty joiners and null elements.
  • Follow best practices for optimal performance and clarity in your code.

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

java.lang.IndexOutOfBoundsException
Aug 21, 2023
Can only iterate over an array or an instance of java.lang.Iterable
Aug 31, 2023
Mastering Method Overloading in Java: A Complete Guide with Examples
Dec 09, 2023
Understanding Call By Reference in C#: A Complete Guide
Dec 09, 2023
Previous in Java
Mastering String Builder in Java: A Complete Guide with Examples
Next in Java
Complete Guide to Array Lists in Java with Examples
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    HTTP Error 500.32 Failed to load ASP NET Core runtime 6,938 views
  • 2
    Error-An error occurred while processing your request in .… 11,273 views
  • 3
    Comprehensive Guide to Error Handling in Express.js 235 views
  • 4
    ConfigurationBuilder does not contain a definition for Set… 19,459 views
  • 5
    Mastering JavaScript Error Handling with Try, Catch, and F… 162 views
  • 6
    Mastering Unconditional Statements in C: A Complete Guide … 21,497 views
  • 7
    Unable to connect to any of the specified MySQL hosts 6,232 views

On this page

🎯

Interview Prep

Ace your Java interview with curated Q&As for all levels.

View Java Interview Q&As

More in Java

  • User-defined data types in java 6285 views
  • Master Java Type Casting: A Complete Guide with Examples 6253 views
  • How to add (import) java.util.List; in eclipse 5850 views
  • org.openqa.selenium.SessionNotCreatedException: session not … 5785 views
  • java.lang.IllegalStateException: The driver executable does … 5122 views
View all Java posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor