Message Formatting

The Java library has a MessageFormat class that formats text with variable parts, like this:

"On {2}, a {0} destroyed {1} houses and caused {3} of damage."

The numbers in braces are placeholders for actual names and values. The static method MessageFormat.format lets you substitute values for the variables. As of JDK 5.0, it is a “varargs” method, so you can simply supply the parameters as follows:

String msg = MessageFormat.format("On {2}, a {0} destroyed {1} houses and caused {3} of
 damage.",
   "hurricane", 99, new GregorianCalendar(1999, 0, 1).getTime(), 10.0E7);

Before JDK 5.0, you had to put the values of the placeholders ...

Get Core Java™ 2 Volume II - Advanced Features, Seventh Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.