You are currently viewing Formatting Messages In Java

Formatting Messages In Java

1. Introduction

Formatting and parsing messages are essential for handling dynamic text in Java applications. Java provides several tools for structuring text output, inserting dynamic values, and extracting information from text. In this article, you will learn how to format text messages efficiently using classes like MessageFormat and ChoiceFormat.

2. Formatting compound messages

The MessageFormat class enables dynamic message formatting with multiple placeholders. The placeholder can be of the following types: dates, times, strings, numbers, currencies, and percentages.
Below is an example of a compound message with placeholders:

Dear {0}, your order #{1} placed on {2} is now {3}

Combining MessageFormat and resource bundles will allow you to format compound messages to fit the user’s location and cultural behaviour.

        Locale locale = Locale.getDefault();
        ResourceBundle bundle = ResourceBundle.getBundle("compound_messages", locale);//Search for messages.properties
        String orderStatusMessage = bundle.getString("order.status.message");
        String customerName = "John Doe";
        String orderNumber = "12345";
        LocalDate orderDate = LocalDate.now();
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d MMMM yyyy", locale);
        String formatedOrderDate = dateFormatter.format(orderDate);
        String status = "shipped";
        String translatedStatus = bundle.getString("status." + status);

        String message = MessageFormat.format(orderStatusMessage, customerName, orderNumber, formatedOrderDate, translatedStatus);
        System.out.println(message);

If you run this program on a system with English as the default Locale, you will get the following output:

Dear John Doe, your order #12345 placed on 28 March 2025 is now shipped.

However, in a French system, the output is the following:

Cher John Doe, votre commande #12345 passée le 28 mars 2025 est maintenant expédiée.

Specify the placeholder type

By default, the MessageFormat class infers the format of the placeholder according to the type of the variable. However, if you need a custom formatting, you should specify a different type.

Dear {0}, your balance is {1,number,currency}.

        Locale locale = Locale.getDefault();
        ResourceBundle bundle = ResourceBundle.getBundle("compound_messages", locale);//Search for messages.properties
        String balanceMessage = bundle.getString("balance.message");
        String customerName = "John Doe";
        double balance = 200.62;

        String message = MessageFormat.format(balanceMessage, customerName, balance);
        System.out.println(message);

Output:

Dear John Doe, your balance is $200.62.

3. Conditional formatting

Conditional formatting allows messages to be adjusted based on specific values. For example, you may need to adjust a word to match the plural form. Java provides ChoiceFormat for handling such cases.

        Locale locale = Locale.getDefault();
        ResourceBundle bundle = ResourceBundle.getBundle("conditional_messages", locale);
        String pattern = bundle.getString("cart.message");
        MessageFormat messageFormat = new MessageFormat(pattern);
        messageFormat.setLocale(locale);
        double[] cartLimits = {0,1,2};

        String [] cartStrings = {
                bundle.getString("noItems"),
                bundle.getString("oneItem"),
                bundle.getString("multipleItems")
        };
        ChoiceFormat choiceFormat = new ChoiceFormat(cartLimits, cartStrings);
        Format[] formats = {choiceFormat, null, NumberFormat.getInstance()};
        messageFormat.setFormats(formats);

        Object[] messageArgumentsZero = {0};
        Object[] messageArgumentsOne = {1};
        Object[] messageArgumentsMultiple = {10};
        String resultZero = messageFormat.format(messageArgumentsZero);
        String resultOne = messageFormat.format(messageArgumentsOne);
        String resultMultiple = messageFormat.format(messageArgumentsMultiple);

        System.out.println(resultZero);
        System.out.println(resultOne);
        System.out.println(resultMultiple);

Running the program above will produce the following output:

You have no items in your cart.
You have one item in your cart.
You have 10 items in your cart.

4. Conclusion

Java provides a rich set of tools for formatting and parsing messages. In this quick article, you learned how to use MessageFormat and ChoiceFormat to format compound messages.

You can find the complete code of this article here in GitHub.

Noel Kamphoa

Experienced software engineer with expertise in Telecom, Payroll, and Banking. Now Senior Software Engineer at Societe Generale Paris.