×

Java Programs

Java Practice

Java program to convert an object of StringJoiner class into a string

Java example to convert an object of StringJoiner class into a string.
Submitted by Nidhi, on June 09, 2022

Problem statement

In this program, we will create an object of StringJoiner class with a specified delimiter, and add the substrings using add() method. Then we will convert the object of StringJoiner into the string using the toString() method and get the characters from the string using the charAt() method.

Java program to convert an object of StringJoiner class into a string

The source code to convert the object of StringJoiner class into the string is given below. The given program is compiled and executed successfully.

// Java program to convert an object of StringJoiner class 
// into the string

import java.util.*;

public class Main {
  public static void main(String[] args) {
    StringJoiner str = new StringJoiner(",");

    str.add("ABC");
    str.add("LMN");
    str.add("PQR");
    str.add("XYZ");

    //Error: Cannot get character using below.
    //System.out.println(str.charAt(2));

    System.out.println(str.toString().charAt(2));
  }
}

Output

C

Explanation

In the above program, we imported the "java.util.*" package to use the StringJoiner class. Here, we created a public class Main.

The Main class contains a main() method. The main() method is the entry point for the program. And, created an object of StringJoiner class str to construct strings with specified delimiter ",". Then we added substrings using add() method. After that, we converted the object of StringJoiner to a string object using the toString() method and accessed a character at index 2 using the charAt() method, and printed the result.

Java StringJoiner Class Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.