×

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

How to Split the String in Java with Delimiter

In Java, splitting strings is a significant and typically used activity while coding. Java gives different ways of dividing the String. The most widely recognized way is to use the...

3 minutes read.

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

Class vs Object in Java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.

Relatively Prime in Java

In this article, you will be very well equipped with a knowledge of a relatively prime number and also Java programs to determine whether a given integer is a relatively...

4 minutes read.

Java Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

Finding Odd Occurrence of a Number in Java

In this tutorial, we will learn how to find the odd occurrence of a number through a java program. Let us consider an array of non-negative integers. Here, except for one...

6 minutes read.

Java Virtual Machine (JVM)

JVM is a virtual runtime environment to execute Java byte codes. The JVM doesn’t understand the keywords we used to write code. That is why it is converted into bytecode. It controls the...

3 minutes read.

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.

Java File Extension

A computer file's suffix is called its file extension. It is easily recognized since it appears immediately after a period (.) in the file name. Consider the file Demo.java as an...

3 minutes read.

Java Math toIntExact() Method

The toIntExact() method of Java Math class returns the int value of the given long argument, throwing an exception if the value overflows an int. Syntax: public static int toIntExact (long value) Parameters: The...

2 minutes read.

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be...

6 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.

Ganesha’s Pattern in Java

This part teaches us how to use stars and other special characters to write Ganesha's Pattern in Java programming. Among the most challenging Java pattern applications to code. The Ganesha will be...

3 minutes read.

Java Integer toOctalString() method

The toOctalString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 8. Syntax public static String toOctalString (int  i) Parameters The parameter ‘i’ represents...

1 minute read.

Hogben Numbers in Java

In this section, we will discover what the Hogben number is and develop Java programs that compute it. Java coding interviews and academic exams typically involve questions about the Hogben...

3 minutes read.

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

String Array in Java

String Array in Java An array is alinear data structure that stores similar type of data. It allows us to store fixed number of elements.It can be of different data types...

6 minutes read.

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 minutes read.

How to download and install Eclipse in Windows?

Download and Install Eclipse on Windows Eclipse is an open source IDE (Integrated Development Environment) which is used to help the programmers to provide a platform to write and run the...

1 minute read.