Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
🧊Introduction
2.
🧊StringJoiner Constructors
3.
🧊StringJoiner Methods
4.
🧊Joining Strings by Specifying Delimiter
5.
🧊Attaching Prefix and Suffix to the String
6.
🧊Merging Two StringJoiner Objects
7.
🧊Methods: setEmptyValue(), length() and toString() 
8.
Frequently Asked Questions
8.1.
What exactly is Java StringJoiner?
8.2.
What is the difference between a prefix and a suffix?
8.3.
Is StringJoiner thread-safe?
8.4.
Which class may join multiple strings with a defined Delimiter and offer a prefix and suffix?
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

StringJoiner Class in Java

Author Kumar Saurav
0 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

🧊Introduction

java.util package, includes a new final class called StringJoiner Class in Java. One can create a sequence of characters with a Delimiter between them. Delimiters like the comma (,), the hyphen (-), and others can now be used to build strings. Additionally, prefixes and suffixes can be passed to the char sequence.

STRINGJOINER CLASS

Also read, Duck Number in Java and Hashcode Method in Java

🧊StringJoiner Constructors

Constructor

Description

Public StringJoiner (CharSequence suffix, CharSequence prefix, CharSequence Delimiter) By employing duplicates of the specified prefix, Delimiter, and suffix, it creates a StringJoiner that is devoid of any characters. If prefix, Delimiter, or suffix are null, NullPointerException is invoked.
Public StringJoiner (CharSequence Delimiter) It creates a StringJoiner devoid of all characters, without a prefix or suffix, and with a duplicate of the specified Delimiter. If the Delimiter is null, NullPointerException is invoked.

Also see,  Swap Function in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

🧊StringJoiner Methods

Method

Description

Public StringJoiner setEmptyValue(CharSequence emptyValue) When this StringJoiner Class in Java is empty, that is, when no elements have been joined yet, it sets the string representation's character set.
Public StringJoiner merge(StringJoiner other) If the StringJoiner Class in Java is not empty, it adds the contents of the StringJoiner without prefix and suffix as the next element. If the given StringJoiner is null, the call has no effect.

 
Public StringJoiner add(CharSequence newElement) If the StringJoiner Class in Java is not empty, it adds the contents of the StringJoiner without prefix and suffix as the next element. If the given StringJoiner is null, the call has no effect.
Public int length() It returns the length of this StringJoiner's String representation.

 

🧊Joining Strings by Specifying Delimiter

StringJoiner Class in Java is used to concatenate numerous strings in this example. We use a hyphen as the Delimiter when we create the StringJoiner object (-).
 

import java.util.StringJoiner;  
public class joiningString 
{  
    public static void main(String[] args) 
	{  
     	/* Passing Hyphen(-) as Delimiter */
        StringJoiner myString = new StringJoiner("-");    
          
        /* We can join multiple strings via add() method  */
        myString.add("Coding");  
        myString.add("Ninjas");  
        myString.add("Welcomes");  
        myString.add("You");  
                  
        /* Print output String */
        System.out.println(myString);  
    }  
}


Output: 

Coding-Ninjas-Welcomes-You

🧊Attaching Prefix and Suffix to the String

ADDING PREFIX AND SUFFIX
import java.util.StringJoiner;  
public class preffix_suffix 
{  
    public static void main(String[] args) 
	{  
     	/* Passing Delimiter - comma(,)  
  	 	Passing Prefix - "(" 
	 	Passing Suffix - ")" */
     	StringJoiner myString = new StringJoiner(",", "(", ")");    
          	
     	/* We can join multiple strings via add() method */
     	myString.add("Coding");  
     	myString.add("Ninjas");  
     	myString.add("Welcomes");  
     	myString.add("You");  
                  	
     	/* Print output String */
     	System.out.println(myString);  
    }  
}


Output:

(Coding,Ninjas,Welcomes,You)


You can also find the output of this java compiler code here.

🧊Merging Two StringJoiner Objects

MERGING
import java.util.StringJoiner;  
public class Merging 
{  
   public static void main(String[] args) 
   {  
		/* Passing Delimiter - comma(,)  
    	Passing Prefix - "(" 
    	Passing Suffix - ")" */
		StringJoiner myString = new StringJoiner(",", "(", ")");    
		myString.add("Coding");  
		myString.add("NInjas");  
		myString.add("Welcomes");  
		myString.add("You");  
		System.out.println("First String: "+myString);
			
		/* Passing Delimiter - hyphen(-)  
    	Passing Prefix - String "pre" 
    	Passing Suffix - String "suff" */
		StringJoiner nextString = new StringJoiner("-", "pre", "suff");    
		nextString.add("Coding");  
		nextString.add("Ninjas");  
		nextString.add("Study");  
		nextString.add("Platform"); 
		System.out.println("Second String: "+nextString);
		StringJoiner mergedString = myString.merge(nextString);   
		System.out.println(mergedString);  
   }  
}


Output:

First String: (Coding,Ninjas,Welcomes,You)
Second String: preCoding-Ninjas-Study-Platformsuff
(Coding,Ninjas,Welcomes,You,Coding-Ninjas-Study-Platform)

 

The StringJoiner class in Java like add() and merge() methods were demonstrated in the preceding examples. Let's take a look at the other methods of this class.

🧊Methods: setEmptyValue(), length() and toString() 

 METHODS
import java.util.StringJoiner;  
public class methods
{  
    public static void main(String[] args) 
    {  
     /*Comma(,) as Delimiter */
        StringJoiner myString = new StringJoiner(",");   
          
        /*We can set the default value with the setEmptyValue() function. This default value will be printed if we print the value of an empty StringJoiner 	           object. */
        myString.setEmptyValue("Coding Ninjas is the best platform");  
        
        /* Because we haven't yet added any strings to StringJoiner, 
        this should show the default value of StringJoiner. */
        System.out.println("Default String: "+myString);   
          
        /* Adding strings to StringJoiner */
        myString.add("Coding");  
        myString.add("Ninjas"); 
        myString.add("Welcomes");
        myString.add("You");
        myString.add("here");
        System.out.println(myString);            
        int l = myString.length();  
        System.out.println("Length of the StringJoiner: "+l);  
          
        /* The toString() method is used for converting a StringJoiner
           instance to a String.  */
        String strg = myString.toString();  
        System.out.println(strg);   
    }  
}


Output:

Default String: Coding Ninjas is the best platform
Coding,Ninjas,Welcomes,You,here
Length of the StringJoiner: 31
Coding,Ninjas,Welcomes,You,here


You can also find the output of this java compiler code here.

Frequently Asked Questions

What exactly is Java StringJoiner?

The ultimate use of StringJoiner is to create a sequence of characters separating from each other using a suitable Delimiter. Optionally beginning with a prefix and ending with a suffix is also used for StringJoiner. 

What is the difference between a prefix and a suffix?

A prefix is a word portion that is added to the start of a word to change its meaning. A suffix is a word part that is added to the end of a word to change its meaning.

Is StringJoiner thread-safe?

Unlike StringBuffer methods (such as append()), StringJoiner methods (such as add()) are not synchronized. As a result, it is not thread-safe.

Which class may join multiple strings with a defined Delimiter and offer a prefix and suffix?

StringJoiner is a new class added to Java 8. utility package.  We can use this class to combine several strings using the given Delimiter. When merging multiple strings, we can also provide a prefix and suffix to the final string.

Conclusion

In the article “StringJoiner Class in Java,” we have started our discussion with the Constructor of StringJoiner Class in Java. Then we have seen the Methods of StringJoiner Class in Java. Then we tried to understand the StringJoiner Class in Java by different examples. Examples like joining strings by specifying Delimiter. Adding prefixes and suffixes to the output string. Merging two strings using StringJoiner Class in Java. Methods and their uses in StringJoiner Class in Java.

Check out this problem - Longest Common Prefix

You can refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.
Happy Learning!

Live masterclass