java.util.StringJoiner

StringJoiner is a class introduced in Java 8 that helps in constructing a sequence of characters separated by a delimiter with optional prefix and suffix.

This eliminates manual string concatenation and makes code cleaner and more readable, especially when formatting lists or reports.

Commonly Used Constructors and Methods

Simple Program

import java.util.StringJoiner;

public class SimpleStringJoinerDemo {
    public static void main(String[] args) {
        StringJoiner joiner = new StringJoiner(", ");
        joiner.add("Java").add("Python").add("C++");
        
        System.out.println("Languages: " + joiner);
    }
}

Problem Statement

LotusJavaPrince and Mahesh are building a reporting tool for a bank that generates summary strings for customers’ linked account types. The string must be:

  • Delimited by |
  • Surrounded by square brackets [ ... ]
  • Handle empty lists gracefully (e.g., show [No Accounts Linked])
import java.util.*;

public class BankAccountJoinerReport {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Step 1: Input customer name
        System.out.print("Enter customer name: ");
        String customerName = scanner.nextLine();

        // Step 2: Input number of linked accounts
        System.out.print("Enter number of linked accounts: ");
        int n = Integer.parseInt(scanner.nextLine());

        // Step 3: Create StringJoiner with prefix and suffix
        StringJoiner accountJoiner = new StringJoiner(" | ", "[", "]");
        accountJoiner.setEmptyValue("[No Accounts Linked]");

        // Step 4: Input account types
        for (int i = 0; i < n; i++) {
            System.out.print("Enter account type #" + (i + 1) + ": ");
            String accountType = scanner.nextLine();
            accountJoiner.add(accountType);
        }

        // Step 5: Print report
        System.out.println("\n--- Account Summary for " + customerName + " ---");
        System.out.println("Linked Accounts: " + accountJoiner);
    }
}

Sample Output 1 (With Accounts)

Enter customer name: Mahesh
Enter number of linked accounts: 3
Enter account type #1: Savings
Enter account type #2: Checking
Enter account type #3: FD

--- Account Summary for Mahesh ---
Linked Accounts: [Savings | Checking | FD]Code language: CSS (css)

Sample Output 2 (No Accounts)

Enter customer name: LotusJavaPrince
Enter number of linked accounts: 0

--- Account Summary for LotusJavaPrince ---
Linked Accounts: [No Accounts Linked]Code language: CSS (css)

The java.util.StringJoiner class simplifies the process of joining strings with delimiters, especially when formatting output or building dynamic strings. Key benefits include:

  • Clean syntax
  • Optional prefix/suffix
  • Safe handling of empty elements with setEmptyValue()
  • Chainable .add() calls
  • Useful for reports, logs, CSV/JSON formats
Scroll to Top