Previous | Next | Trail Map | Internationalization | Contents

Message Formatting

We all like to use programs that let us know what's going on. Programs that keep us informed often do so by displaying status and error messages. Of course, these messages need to be translated so they can be understood by end-users around the world. We discussed translatable text messages in Isolating Locale-specific Objects in a ResourceBundle. Usually, after you move a message String into a ResourceBundle, you're done. However, if a message contains variable data, you'll have to take some extra steps to prepare it for translation.

In the following list of messages, we've underlined the variable data:

The disk named MyDisk contains 300 files.
The current balance of account #34-98-222 is $2,745.72.
405,390 people have visited your website since January 1, 1998.
Delete all files older than 120 days.
You might be tempted to construct the last message in the preceeding list by concatenating phrases and variables:
double numDays;
ResourceBundle mssgBundle;
.
.
.
String message = mssgBundle.getString("deleteolder") +
                 numDays.toString() + 
                 mssgBundle.getString("days");
This approach works fine in English, but it won't work for languages where the verb appears at the end of the sentence. Because the word order of this message is hardcoded, your localizers won't be able to create grammatically correct tranlations for all languages.

How can you make your program easy to localize if you need to use concatenated messages? You can do so by using the MessageFormat class, which is the topic of this lesson.

Dealing with Concatenated Messages

A concatenated message may contain several kinds of variables: dates, times, strings, numbers, currency, and percentages. To format a concatenated message in a locale-independent manner, you construct a pattern that you apply to a MessageFormat object.

Handling Plurals

The words in a message usually vary if both plural and singular word forms are possible. With the ChoiceFormat class, you can map a number to a word or phrase, allowing you to construct messages that are grammatically correct.


Previous | Next | Trail Map | Internationalization | Contents