×

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

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is...

3 minutes read.

Java Viva Questions and Answers

Question: Explain Java programming language. Answer: It is a high-level programming language. This programming language is based on the principles of object-oriented programming. Large-scale applications can be developed by using this...

16 minutes read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

Java Class Keyword

We know that java is object-oriented programming language which contains the essential key concepts such as classes and objects etc to have clear idea about the object-oriented programming.Java is mainly...

3 minutes read.

How to run Java Program?

How to run Java Program In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad. In order to run a Java program, we...

2 minutes read.

Series Program in Java

Series Program in Java The series program in Java is written to print the mathematical series such as the Fibonacci series, Pell series, etc. A few of the renowned series are...

12 minutes read.

How Many Ways to Create Objects in Java

Introduction Java comes under the category of object-oriented programming languages. Since it is object-oriented, everything in Java is considered an object. Java is a diverse programming language that is designed to...

6 minutes read.

Default Virtual Behaviour in C++ vs Java

Virtual Behaviour in C++: The class member methods in C++ are, by default, non-virtual. This implies that by simply defining it, they can be turned into virtual. The virtual class can be...

3 minutes read.

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

Java Math hypot() Method

The hypot() method of Math class returns the square root for the expression x2 + y2 without the intermediate underflow or overflow . Syntax: public static double hypot(double x, double y) Parameters: The parameters...

2 minutes read.

Java Int Keyword

Among the primitive data types is the Java int keyword. To declare variables, use this. It can also be used with methods that return values of the integer type. It...

3 minutes read.

Differences and Similarities between HashSet, LinkedHashSet and TreeSet in Java

HashSet Class: The HashSet is a class that executes the Setpoint of interaction. It is utilised to store the items in a hashtable; a hashtable is an information structure which holds...

10 minutes read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

Matrix Multiplication in Java

In Java, using the binary operator (*) we can perform matrix multiplication. A Matrix is a group of arrays. In the multiplication of matrices, the elements of each row are...

3 minutes read.

Java Wrapper classes

Java Wrapper classes A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects. Wrapper...

2 minutes read.

How to compare characters in Java

In this tutorial, we will learn about how to compare characters in Java. To compare characters in Java, we will learn about what is a character in Java Char The character is...

4 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Access specifiers in Java

What are access specifiers in Java? Access specifiers in Java are used to determine whether other classes can use a particular field or invoke a particular method. Access specifiers mainly specify...

7 minutes read.