×

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the provided suffix.

This class is found in java.util package. This class is declared with final. This class extends the Object class.

Stringjoiner Constructors:

1. Public StringJoiner (Char_Sequence delimiter)
This is an in-built parameterized constructor in the class StringJoiner. This takes in the delimiter, an constructs a StringJoiner having 0 characters in it. This StringJoiner neither has prefix nor suffix. So, if the provided delimiter is null, a NullPointerException is thrown.

2. Public StringJoiner (Char_Sequence delimiter, Char_Sequence prefix, Char_Sequence suffix)

Another parameterized constructor in the StringJoiner class. This class takes in three parameters which constitutes the delimiter and a prefix followed by suffix.

So, as the prefix and suffix parameters are provided, this will generate a StringJoiner having the copies of the supplied prefix, delimiter and suffix with 0 characters in it. If any one of the provided parameters, delimiter, prefix, suffix is null, a NullPointerException is thrown.

These are the in-built constructors in the StringJoiner Class. We can add our own constructors to this also, by extending StringJoiner class.

StringJoiner Methods:

There are many methods that are to be utilized for direct implementation. Some of the methods are:

1. add Method

The prototype for this method goes with

Public StringJoiner add (Char_Sequence    newElement)

This method adds the copy of the provided newElement or Char_Sequence value to the StringJoiner value. This new element value can be null also. If the value is null, then null is added to the StringJoiner.

2. merge Method

The prototype for this method goes with

Public StringJoiner merge (StringJoiner other)

This method takes in a StringJoiner and adds the given StringJoiner contents as the next element without any prefix or suffix. If the given StringJoiner is empty or null, there will be no effect of performing the merge function.

3. Length Method

The prototype for this method goes with

Public int length ()

This method doesn’t takes in any parameters but can determine the length of the StringJoiner and returns the length of the StringJoiner of Integer type. 

4. setEmptyValue Method

The prototype for this method goes with

Public   StringJoiner   setEmptyValue (Char_Sequence    empty Value)

This method is generally used when we are determining the string representation of the StringJoiner with no elements are added yet.

5. toString Method

The prototype for this method goes with

Public    String    toString ()

For converting the StringJoiner to String, we will implement the toString method. So, this method returns the String value. This method will return all the prefix, suffix and the values added so far into the StringJoiner. So, if no values are added to the this method will return the prefix and suffix only.

Let’s look into the implementation of the StringJoiner in java

import java. io. * ;
import java. util. StringJoiner;
//Importing the package having StringJoiner.


public class StringJoinerDemo
{
public static void main (String [] args)
{
StringJoiner JoiningNames = new StringJoiner (",");
//Creating an object for StringJoiner Class.
JoiningNames. add ("Mahesh");
JoiningNames. add ("Kalavathi");
JoiningNames. add ("Peter");
JoiningNames. add (“Ayaan”);
JoiningNames. add (“Arha”);
//Add values using add method.


System.out.println (JoiningNames);
}
} 

OUTPUT:

C: \Java> Mahesh, Kalavathi, Peter, Ayaan, Arha

So, in the above program the names are added to the StringJoiner object one by one. And if the object is printed, all the names are given separating every name with “,”.

StringJoiner Example for a StringJoiner with added prefix and suffix

import java.io.*;
import java. util. StringJoiner;
//Importing the package having StringJoiner.


public class StringJoinerDemo
{
public static void main (String [] args)
{
StringJoiner JoiningNames = new StringJoiner (",", “(“, “)”);
//Creating an object for StringJoiner Class.
JoiningNames. add ("Mahesh");
JoiningNames. add ("Kalavathi");
JoiningNames. add ("Peter");
JoiningNames. add (“Ayaan”);
JoiningNames. add (“Arha”);
//Add values using add method.


System.out.println (JoiningNames);
}
} 

OUTPUT:

C: \Java>(Mahesh, Kalavathi, Peter, Ayaan, Arha)

The above code snippet has a call to the parameterized constructor in the StringJoiner class. This constructor takes in the delimiter, prefix and the suffix values.

Let’s understand the toString () Method by implementing in a java program.

import java. io. * ;
import java. util. StringJoiner;
//Importing the package having StringJoiner.
public class StringJoinerDemo
{
public static void main (String [] args)
{
StringJoiner strr = new StringJoiner (“  “);
//Creating an object for StringJoiner Class.


strr. add(“Programming”);
strr. add(“is”);
strr. add(“Human”);
strr. add(“Interaction”);
strr. add(“with”);
strr. add(“Computer.”);
  //Add the values to the StringJoiner using the add method.

System.out.println (“StringJoiner: “, strr.toString ());
//Converting the StringJoiner to String using toString.
}
}

OUTPUT:

C: \Java> java StringJoinerDemo
Programming is Human Interaction with Computer.

In the above code snippet, all the values are added into the StringJoiner by using the add Method. At last, the StringJoiner is converted into the string by using the toString Method.

StringJoiner Example for merging two StringJoiner.
import java.io.*;
import java.util.StringJoiner;
public class StringJoinerDemo
{
Public static void main(String args[])
{
StringJoiner JoiningNames = new StringJoiner(“;”, “{“, “}”);
JoiningNames.add(“Krish”);
JoiningNames.add(“Peter”);
//Creating a StringJoiner with two names.


StringJoiner JoiningNames2 = new StringJoiner(“,”, “{“, “}”);
JoiningNames2.add(“Steven”);
JoiningNames2.add(“Stella”);
//Creating another StringJoiner with another two names.


StringJoiner mergeobj = JoiningNames.merge (JoiningNames2);
//Merging two StringJoiner into one. 
System.out.println (mergeobj);
//Printing the merged object.
} //main
} //StringJoinerDemo

OUTPUT:

C: \Java>java StringJoinerDemo
[Krish; Peter; Steven, Stella]

In the above code snippet, we created two StringJoiner and using another StringJoiner, these two StringJoiner are merged into one.

This is how merge Method in the StringJoiner class works.

StringJoiner class Methods Example

import java.io.*;
import java.util.StringJoiner;  
public class StringJoinerDemo 
{  
 public static void main (String [] args) 
{  
        StringJoiner joiningNames = new StringJoiner (","); 
// passing comma (,) as delimiter   
          
    // Prints nothing as it is empty  
        System.out.println (joiningNames);  
          
        // setting a default empty value using the Method setEmptyValue.  
        joiningNames.setEmptyValue ("StringJoiner is empty");  
                System.out.println (joiningNames);  
          
          
        // Adding values to StringJoiner one by one.  
        joiningNames.add ("Rohan");  
        joiningNames.add ("Ramya");  
        System.out.println (joiningNames);  
          
        // Returns length of StringJoiner using the length method of the StringJoiner class.  
        int length = joiningNames.length ();  
        System.out.println ("Length: "+length);  
          
        // Returns StringJoiner as String type   
        String strr = joiningNames.toString ();  
        System.out.println (strr);  
          
        // Now, we can apply String methods on it  
        char chr = str. charAt (2);  
        System. out. println ("Character at index 2: "+chr);  
          
        // Adding another more element   
        joiningNames. add ("Sirish");  
        System. out. println (joiningNames);  
          
        // Returns length  
        int new_Length = joiningNames. length ();  
        System. out. println ("New Length: "+new_Length);  
    } //main
} // StringJoinerDemo

OUTPUT:

C:/java> java StringJoinerDemo
StringJoiner is empty
Rohan, Ramya
Length: 11
Rohan, Ramya
Character at index 2: h
Rohan,Ramya,Sirish
New Length: 18

Related Topics

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

Ramanujan Number or Taxicab Number in Java

In this section, we will discuss what a Ramanujan number (also known as a Hardy-Ramanujan number) is and how to use a Java programme to determine if a given integer...

3 minutes read.

PriorityBlockingQueue Class in Java

What is the Queue? An abstract data structure like Stacks is a queue. A queue is open on both ends. Data is always pushed to one end, called enqueue, and removed...

4 minutes read.

Method chaining in Java

Method chaining in Java is the act of calling a series of methods one after the other. The sole distinction between it and function Object () constructor chaining is the difference...

3 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

Object Oriented Programming (OOPs)

Since the dawn of earth, we have kept on evolving. The need for evaluation comes with the aim of improving the existing systems when something inappropriate is found for the...

5 minutes read.

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

Swastika Pattern in Java

This part teaches us how to create the Swastika Pattern in Java utilizing user-defined columns and rows as well as stars or other special characters.A Java pattern application that is...

2 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

Java FileNotFoundException

FileNotFoundException is another exception class accessible in the java.io bundle. The exemption happens when we attempt to get to that document which isn't accessible in the framework. It is a checked...

5 minutes read.

How to remove special characters from String in Java

Strings in Java are Objects that are supported inside by a burn exhibit. Since exhibits are immutable (cannot develop), Strings are changeless too. A completely new String is made whenever...

5 minutes read.

How to run Java Program in Command Prompt

How to run Java Program in Command Prompt In this section, we will learn how to write, save, compile, and execute or run a Java program in the Command Prompt. Note: One...

3 minutes read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.

What are Array strings in Java?

In normal programming, An array is a group and a collection of identical forms of data that are stored in a sequential memory region and may be accessed using their...

4 minutes read.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

Java Architecture

Java architecture is a combination of three parts they are JVM, JRE and JDK. These components will help in the functioning of the java programs. The process of code interpretation...

6 minutes read.

Segment Tree in Java

Binary trees can address a variety of issues; however, the Segment Tree is more efficient in terms of time complexity. The segment tree in Java is represented using an array. Native...

4 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.