Fun With MessageFormat

The java.text.MessageFormat class is one those classes that you need to use at least once during your practice of The Dark Arts.
Its purpose is really quite simple. It takes in a bunch of objects, formats them, and then places them into the given pattern in the appropriate places.

We will be calling the following method in the MessageFormat class.

public static String format(String pattern, Object ... arguments)

This method takes in a pattern and a variable argument list (varargs).

System.out.println(MessageFormat.format('{0,date,full}', System.currentTimeMillis()));

The ‘0’ is the position in the argument list of the variable that we want to use. ‘time’ is the format type. ‘full’ is the format style.

You can use your own format style to give you what you need.

System.out.println(MessageFormat.format('{0,date,yyyyMMdd}', System.currentTimeMillis()));

If a format style is not specified a default will be used.

System.out.println(MessageFormat.format('{0,number}', System.currentTimeMillis()));

This can then be formatted to remove the commas.

System.out.println(MessageFormat.format('{0,number,#}', System.currentTimeMillis()));

Here’s another example.

System.out.println(MessageFormat.format('Greetings {0}! You are visitor no {1,number,integer} The time is now {2,time,short}. Today is {2,date,short}', 'Bob', 23, System.currentTimeMillis()));

You will notice firstly that the variable positions are zero-based. No formatting is given for the first variable. The variable gets treated as plain text.

Well that’s a really basic and brief intro to the MessageFormat class. It’s really easy to use and can make life worth living. 😉

Check the API for a full listing of format types and styles. As with anything, always read the API documentation to get a better understanding.

Have fun!

UPDATE: Check out the links section for more about MessageFormat.