O'Reilly logo

Core Java® Volume II—Advanced Features, Ninth Edition by Gary Cornell, Cay S. Horstmann

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.5. 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.0E8);

In this example, the placeholder {0} is replaced with "hurricane", {1} is replaced with 99, and so on.

The result of our example ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required