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

41,491

Solution 1

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.

Solution 2

String.format is just a shortcut to Formatter, this is a "printf-style" formatter. On the other side, MessageFormat uses a different formatting convention, as described in the linked documentation.

Use the first "for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output" and the second "to produce concatenated messages in language-neutral way".

Share:
41,491

Related videos on Youtube

kedar kamthe
Author by

kedar kamthe

I am a self-motivated software engineer. Programming is not just a job to me; it is a passion. I started my career early upon obtaining my Bachelor's Degree in Computer Science, but my eagerness to program started way before my academic training. I live in Pune, India and work as Sr. Java developer with a reputed firm.

Updated on July 15, 2020

Comments

  • kedar kamthe
    kedar kamthe almost 4 years

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

  • Pieter De Bie
    Pieter De Bie over 7 years
    You have somewhat control over formatting in MessageFormat.format though, ie: "{0,number,integer}".
  • Greg Brown
    Greg Brown over 4 years
    Format strings also support positional arguments (e.g. "%2$s" formats the second argument as a string).
  • Greg Brown
    Greg Brown over 4 years
    This does seem to be the recommended approach, but I'm still struggling to understand why. Both support positional arguments, and MessageFormat's lack of time zone support makes it considerably less appealing.