Java program to merge two strings Constructed using StringJoiner class

Java example to merge two strings Constructed using StringJoiner class.
Submitted by Nidhi, on June 09, 2022

Problem Solution:

In this program, we will create two strings using StringJoiner class with a specified delimiter, and add the substrings using add() method. Then we will use the merge() method to merge the created strings.

Program/Source Code:

The source code to merge two strings Constructed using StringJoiner class is given below. The given program is compiled and executed successfully.

// Java program to merge two strings Constructed 
// using StringJoiner class

import java.util.*;

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

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

    str2.add("111");
    str2.add("222");
    str2.add("333");
    str2.add("444");

    str1.merge(str2);

    System.out.println("Constructed String is: '" + str1 + "'");
  }
}

Output:

Constructed String is: 'ABC,LMN,PQR,XYZ,111:222:333:444'

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 two objects of StringJoiner class str1, and str2 to construct strings with specified delimiter ",". Then we added substrings using add() method. After that, we merged the str2 with str1 and printed the updated str1.

Java StringJoiner Class Programs »






Comments and Discussions!

Load comments ↻






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