Krithika Vittal
Krithika Vittal

Reputation: 1477

Pros and cons of using MessageFormat

Is it advisable to use java.text.MessageFormat to do operations on Strings? Or any alternative?

Upvotes: 0

Views: 865

Answers (2)

Sai Ye Yan Naing Aye
Sai Ye Yan Naing Aye

Reputation: 6738

The advantages of using MessageFormat are

  • The message format will come from resources, and the arguments will be dynamically set at runtime.
  • The message format API is a great way to abstract the general structure of a message from the actual content.
  • MessageFormat takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places

The disadventages of using MessageFormat is

  • The rules for using quotes within message format patterns unfortunately have shown to be somewhat confusing.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533580

IMHO, MessageFormats are particularly useful when you need to define them externally, e.g. via a Resource.

You can have different MessageFormats for different languages and they can present your fields in a different order suitable to the language.

For the simplest of needs I would use String + e.g.

out.println("Message: " + message+", count: "+ count);

For more complex formatting needs I would use String format.

put.printf("Percent %6.2f%%, bytes: %,d%n", percent, byteCount);

Where you need to be able to configure your message format, I believe MessageFormat is likely to be the best option.

Upvotes: 1

Related Questions