String template = "Hello, {0}!"; // Use MessageFormat to format the message with the user's name String message = MessageFormat.format(template, "Alice"); // Output: Hello, Alice! System.out.println(message);
String template = "Your payment of ${0} was received on {1,date,long}."; // Use MessageFormat to format the message with the payment amount and date double paymentAmount = 123.45; Date paymentDate = new Date(); String message = MessageFormat.format(template, paymentAmount, paymentDate); // Output: Your payment of $123.45 was received on December 31, 2021. System.out.println(message);In this example, the placeholders `{0}` and `{1,date,long}` are replaced with the payment amount and payment date, respectively. The `date,long` format specifier is used to format the payment date as a long date string. Overall, the MessageFormat class from the `java.text` package library provides a flexible way to create messages with placeholders that can be customized at runtime.