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

前端 未结 2 1717
离开以前
离开以前 2020-12-23 18:33

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

2条回答
  •  再見小時候
    2020-12-23 19:19

    Put simply, the main difference is in format string:

    1. MessageFormat.format() format string accepts argument positions (eg. {0}, {1}). Example:

      "This is year {0}!"

      The developer doesn't have to worry about argument types, because they are, most often, recognized and formated according to current Locale.

    2. String.format() format string accepts argument type specifiers (eg. %d for numbers, %s for strings). Example:

      "This is year %d!"

      String.format() generally gives you much more control over how the argument is displayed thanks to many options you can specify with the type specifier. For instance, format string "%-6.2f" specifies to display a left-aligned floating point number with min. width 6 chars and precision of 2 decimal places.

    Just have a look at javadoc of both methods to find out more details.

提交回复
热议问题