MessageFormat

The MessageFormat class in java.text package is used to produce concatenated messages that include dynamic values, such as numbers, dates, or strings, in a template format. Unlike string concatenation, MessageFormat is locale-sensitive and cleaner for formatting complex messages with placeholders.

Key Features:

  • Supports indexed placeholders like {0}, {1}, etc.
  • Can format numbers, dates, and strings.
  • Localized formatting.
  • Reusable format templates.

Common Used Methods

Simple Program

import java.text.MessageFormat;

public class SimpleMessageFormatExample {
    public static void main(String[] args) {
        String pattern = "Hello {0}, you have {1} new messages.";

        String formattedMessage = MessageFormat.format(pattern, "Mahesh", 5);

        System.out.println(formattedMessage);
    }
}
/*
Hello Mahesh, you have 5 new messages.
*/

Problem Statement

Paani and Mahesh are building a Bank Notification System. Whenever a transaction occurs, the system should send a personalized notification to the customer with the following details:

  • Customer Name
  • Transaction Amount
  • Transaction Type (Credit/Debit)
  • Current Balance

Use the MessageFormat class to create such a dynamic message template.

import java.text.MessageFormat;

public class BankNotificationSystem {

    public static void main(String[] args) {
        // Pattern with placeholders
        String pattern = "Dear {0}, your account has been {1} with ₹{2,number,#,##0.00}. "
                       + "Your current balance is ₹{3,number,#,##0.00}.";

        // Sample data for multiple customers
        Object[][] transactions = {
            {"Mahesh", "credited", 2500.75, 10500.50},
            {"LotusJavaPrince", "debited", 1200.00, 8800.50},
            {"Paani", "credited", 7000.00, 15800.75}
        };

        System.out.println("----- Bank Notifications -----");
        for (Object[] transaction : transactions) {
            String message = MessageFormat.format(pattern, transaction);
            System.out.println(message);
        }
    }
}
/*
----- Bank Notifications -----
Dear Mahesh, your account has been credited with ₹2,500.75. Your current balance is ₹10,500.50.
Dear LotusJavaPrince, your account has been debited with ₹1,200.00. Your current balance is ₹8,800.50.
Dear Paani, your account has been credited with ₹7,000.00. Your current balance is ₹15,800.75.
*/

The MessageFormat class in Java offers a clean and structured way to build messages with dynamic values, making it ideal for logs, notifications, and multi-language applications.MessageFormat is a vital class when building user-friendly messages with variable data, especially in enterprise and internationalized applications.

Scroll to Top