Real World Example

Generating an Invoice and Masking Data

Billing systems build invoice text line by line with StringBuilder, and payment apps mask card numbers and phone numbers before showing or logging them.

Example

public class Main {
    static String maskCard(String card) {
        String last4 = card.substring(card.length() - 4);
        return "*".repeat(card.length() - 4) + last4;
    }

    static String maskPhone(String phone) {
        return phone.substring(0, 2) + "******" + phone.substring(8);
    }

    public static void main(String[] args) {
        String[][] items = { { "Wireless Mouse", "1", "799" }, { "USB-C Hub", "2", "1499" }, { "Laptop Stand", "1", "1199" } };

        StringBuilder inv = new StringBuilder();
        String line = "-".repeat(38);
        inv.append("INVOICE INV-2024-001").append(System.lineSeparator());
        inv.append(line).append(System.lineSeparator());
        int total = 0;
        for (String[] it : items) {
            int qty = Integer.parseInt(it[1]);
            int amount = qty * Integer.parseInt(it[2]);
            total += amount;
            inv.append(String.format("%-18s x%-3d %10s%n", it[0], qty, String.format("%,d", amount)));
        }
        inv.append(line).append(System.lineSeparator());
        inv.append(String.format("%-23s %10s%n", "TOTAL (Rs)", String.format("%,d", total)));
        inv.append("Paid with card ").append(maskCard("4111222233334444"));
        inv.append(System.lineSeparator()).append("Contact ").append(maskPhone("9876543210"));
        System.out.println(inv);
    }
}

Output

INVOICE INV-2024-001
--------------------------------------
Wireless Mouse     x1          799
USB-C Hub          x2        2,998
Laptop Stand       x1        1,199
--------------------------------------
TOTAL (Rs)                   4,996
Paid with card ************4444
Contact 98******10