Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 396
kedar kamthe Avatar asked May 11 '10 09:05

kedar kamthe


People also ask

What is format and string format?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Parameter: The locale value to be applied on the format() method.

What is MessageFormat format ()?

MessageFormat provides a means to produce concatenated messages in a language-neutral way. Use this to construct messages displayed for end users. MessageFormat takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.

What does string format mean in Java?

The Java String. format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale.

What is the format () method in Java string What is the difference between the format () method and the printf () method?

The key difference between them is that printf() prints the formatted String into console much like System. out. println() but the format() method returns a formatted string, which you can store or use the way you want.


2 Answers

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.

like image 111
Adam Dyga Avatar answered Sep 22 '22 15:09

Adam Dyga


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".

like image 45
lbalazscs Avatar answered Sep 21 '22 15:09

lbalazscs