Class MessageFormat in Java With Example

5
1589
Spread the love
  • 23
  • 34
  • 28
  • 35
  •  
  •  
  •  
  • 12
  •  
  •  
    132
    Shares

What this article will cover?

MessageFormat in Java, MessageFormat in java example, MessageFormat java API, MessageFormat java class and how to use MessageFormat in java

MessageFormat in Java

MessageFormat is a class that helps to format a message String. It also helps to substitute objects into the predefined position in the message String.

The MessageFormat class constructs textual messages using a formatting pattern string. Conceptually, the class functions much like printf() in C. Syntactically, however, it is quite different. A MessageFormat object uses a pattern string; formatted arguments are placed into the pattern string to produce a resulting string. Arguments are delimited by matching sets of curly braces and may include additional information about how that data should be formatted. For example, consider the following code:

String message =
"Boot of server {0}began at {1, time}on {1, date, full}.";
MessageFormat boot = new MessageFormat(message);
Date now = new Date();
Object[] arguments = {"luna3", now};
System.out.println(boot.format(arguments));

This code produces the following output:
The boot of server luna3 began at 11:13:22 AM on Monday, March 03, 1997.
Each of the arguments is numbered and includes an optional type and an optional style. In the example above, {1, date, full} indicates that the argument at index 1 in the argument array should be formatted using a DateFormat object with the FULL style. The allowed types and styles are:

Type Object available Styles
date DateFormat short, medium, long, full, pattern
number NumberFormat integer, percent, currency, pattern
time DateFormat short, medium, long, full, pattern
choice ChoiceFormat pattern

For the date and time types, the styles correspond to the styles, or lengths, of the resulting date and time strings. We can also specify a date or time pattern string as we would for creating a SimpleDateFormat object. For the number type, the styles correspond to formatting normal numbers, percentage values, and currency values. We can also specify a number pattern string as we would for creating a DecimalFormat object. For the choice type, we can specify a choice pattern as we would for creating a ChoiceFormat object. If no type is specified, the argument should be a string.

The following example shows how to use a choice format pattern with a MessageFormat:

Object[] arguments = {new Integer(1)};
String grammar = "At last count, {0}server{0, choice, 0#s|1#|1<s}
{0, choice, 0#were|1#was|1<were}booted.";
MessageFormat booted = new MessageFormat(grammar);
System.out.println(booted.format(arguments));
arguments[0] = new Integer(2);
System.out.println(booted.format(arguments));

This example produces the following output:
At last count, 1 server was booted.
At last count, 2 servers were booted.

As an alternative to specifying all of the formattings in the pattern string, we can use an array of Format objects to format the arguments. We can specify this array using setFormats().Note We create MessageFormat objects directly, rather than through factory methods. This is because MessageFormat does not implement any locale-specific behavior. To produce properly internationalized output, the pattern string that is used to construct a MessageFormat should come from a ResourceBundle instead of being embedded in the code.

MessageFormat in java example

If we want to display a message multiple times, MessageFormat helps a lot. We can achieve the same by creating an object of  MessageFormat class by giving the pattern string. Once the object has been created, we can call the format() method (defined in this class) with the array of objects to be formatted into the output message.

The same method can be applied if we want to format the message only one time. In that case, we need to call the format() method with a message or pattern string or an array of argument objects. They will be formatted and substitute for the message.

The message or pattern should clearly state where each argument should be a substitute. We can obtain this by digits enclosed in curly braces.

Example-

If the pattern is “{0}” it signifies that the first object needs to be substituted with a string. Similarly “{5}” signifies that the sixth object needs to be substituted with a string.

Just in case the object that needs to be inserted is not String, the JVM checks if the same is an instance of Date or Number or the subclass of Date or Number.

If they are an instance of Date or Number or the subclass of Date or Number, MessageFormat insert them with default DateFormat or NumberFormat.

If they are not an instance of Date or Number or the subclass of Date or Number, MessageFormat insert them by invoking the object’s toString() method to convert.

The applicable and default patterns are:

  • date
  • time
  • number
  • choice

They will be autoformatted as date, time, number and choice before substituting them into pattern String.

However, they need to be separated by a comma.

The class structure of MessageFormat java class is given as

public class java.text.MessageFormat extends java.text.Format{
// Public Constructor
public MessageFormat(String pattern);
// Class Methods
public static String format(String pattern, Object[] arguments);
// Public Instance Methods
public void applyPattern(String newPattern);
public Object clone(); // Overrides Format
public boolean equals(Object obj); // Overrides Object
public final StringBuffer format(Object[] source, StringBuffer result,FieldPosition ignore);
public final StringBuffer format(Object source, StringBuffer result,FieldPosition ignore); // Defines Format
public Format[] getFormats();
public Locale getLocale();
public int hashCode(); // Overrides Object
public Object[] parse(String source, ParsePosition status);
public Object[] parse(String source) throws ParseException;
public Object parseObject(String text, ParsePosition status);
// Defines Format
public void setFormat(int variable, Format newFormat);
public void setFormats(Format[] newFormats);
public void setLocale(Locale theLocale);
public String toPattern();
}

The details of the class structure are given as follows:

public MessageFormat(String pattern);

public MessageFormat(String pattern) constructor creates a MessageFormat with the given formatting pattern string.

Parameter
pattern – The pattern string.

public static String format(String pattern, Object[] arguments);

public static String format(String pattern, Object[] arguments) method is interesting.Calling this static method is equivalent to constructing a MessageFormat using the given formatting pattern string and asking it to format the given arguments with the format() method.

Parameter
pattern – The pattern string.
arguments – An array of arguments.

public void applyPattern(String newPattern);

public void applyPattern(String newPattern) method tells this MessageFormat to use the given formatting pattern to format and parse arguments.

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 23
  • 34
  • 28
  • 35
  •  
  •  
  •  
  • 12
  •  
  •  
    132
    Shares

5 COMMENTS

  1. Heya i am for the first time here. I found this board and I find It really useful & it helped me out a lot. I hope to give something back and help others like you aided me.

  2. Someone essentially assist to make critically articles I might state.
    That is the very first time I frequented your web page and up to
    now? I surprised with the research you made to create this particular submit extraordinary.
    Excellent activity!

  3. We’re a group of volunteers and starting a brand new scheme in our
    community. Your website provided us with helpful information to
    work on. You have performed an impressive job and our whole community will be grateful to you.

  4. Hello There. I found your blog the use of msn. That is
    a very smartly written article. I’ll be sure to bookmark it and come back to read extra of your helpful info.
    Thanks for the post. I’ll definitely comeback.

  5. Excellent beat ! I would like to apprentice while you amend your website, how could
    i subscribe for a blog web site? The account aided me a acceptable deal.
    I had been a little bit acquainted of this your broadcast provided bright clear
    idea

LEAVE A REPLY

Please enter your comment!
Please enter your name here