Difference between MessageFormat.format and String.format in jdk1.5?

What is the difference between MessageFormat.format and String.format in JDK 1.5?

+42
java string-formatting messageformat
May 11 '10 at 9:55 a.m.
source share
2 answers

Simply put, the main difference is in the format string:

  • <line>

MessageFormat.format() takes the position of the arguments (for example, {0} , {1} ). Example:

"This is year {0}!"

The developer does not need to worry about the types of arguments, since they are most often recognized and configured in accordance with the current Locale .

Format string

String.format() accepts arguments of type argument (for example, %d for numbers, %s for strings). Example:

"This is year %d!"

String.format() usually gives you more control over how the argument is displayed, thanks to many parameters that you can specify with a type specifier. For example, the format string "%-6.2f" indicates the display of the left- "%-6.2f" floating-point number with min. 6 characters wide and 2 decimal places precision.

Just look at the javadoc of both methods for more details.

+47
Feb 18 '13 at 14:12
source share

String.format is just a shortcut to Formatter , it is a printf formatter. MessageFormat , on the other hand, uses a different formatting convention, as described in the related documentation.

Use the first "to align and align the layout, common formats for numeric, string, and date / time data and locale-dependent output," and the second "to create concatenated messages in a neutral language."

+14
Feb 18 '13 at 13:59
source share



All Articles