Class MessageFormat in Java With Example

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.

Ads code goes here

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:

TypeObjectavailable Styles
dateDateFormatshort, medium, long, full, pattern
numberNumberFormatinteger, percent, currency, pattern
timeDateFormatshort, medium, long, full, pattern
choiceChoiceFormatpattern

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.

READ  Class FileDescriptor in Java

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.

READ  Class Byte in Java

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.

Parameter
pattern – The pattern string.

public Object clone();

public Object clone() method creates a copy of this MessageFormat and then returns it.

This method returns a copy of this MessageFormat.

public boolean equals(Object obj);

public boolean equals(Object obj) method returns true if obj is an instance of MessageFormat and is equivalent to this MessageFormat.

This method returns true if the objects are equal; false if they are not.

Parameter
obj – The object to be compared with this object.

public final StringBuffer format(Object[] source, StringBuffer result,FieldPosition ignore);

public final StringBuffer format(Object[] source, StringBuffer result, FieldPosition ignore) method formats the given object and appends the result to the given StringBuffer. The method assumes that the given object is an array of arguments.

This method returns the given buffer result with the formatted representation of the object appended to it.

Parameter
source – The object to be formatted.
result – A StringBuffer on which to append the formatted information.
ignore – Ignored.

public final StringBuffer format(Object source, StringBuffer result,FieldPosition ignore);

public final StringBuffer format(Object source, StringBuffer result,FieldPosition ignore) method formats the given arguments in the object array and appends the result to the given StringBuffer.

This method returns the given buffer result with the formatted representation of the object array appended to it.

Parameter
source – The object array to be formatted.
result – A StringBuffer on which to append the formatted information.
ignore – Ignored.

public Format[] getFormats();

public Format[] getFormats() method returns the format objects that this MessageFormat uses. Note that formats are numbered according to the order in which they appear in the formatting pattern string, not according to their specified argument numbers.

This method returns an array of the formats used by this MessageFormat.

public Locale getLocale();

public Locale getLocale() method returns the locate for this MessageFormat. This locale is used to get default date, time, and number formatters.

This method returns the Locale of this MessageFormat

public int hashCode(); 

public int hashCode(); method returns a hashcode for this MessageFormat.

This method returns a hashcode for this object.

public Object[] parse(String source, ParsePosition status);

public Object[] parse(String source, ParsePosition status) method

This method returns an array of objects represented by the test starting at the given position.
Parameter
source – The string to be parsed.
status – A ParsePosition object that specifies a position in the string.

public Object[] parse(String source) throws ParseException;

public Object[] parse(String source) throws ParseException method parses arguments from the given string, which should be in the format given by the formatting pattern string of this MessageFormat. If the string is not correctly formatted, an exception is thrown.

READ  Abstract Interface FilenameFilter in Java

This method returns an array of objects represented by the given string.

Parameter
source – The string to be parsed.

public Object parseObject(String text, ParsePosition status);

public Object parseObject(String text, ParsePosition status) method parses arguments from the given string, starting at the specified position. The string should be in the format given by the formatting pattern string of this MessageFormat.

This method returns an array of objects represented by the test starting at the given position.
Parameter
source – The string to be parsed.
status – A ParsePosition object that specifies a position in the string.

public void setFormat(int variable, Format newFormat);

public void setFormat(int variable, Format newFormat) method sets the Format object that is used for the given argument in the formatting pattern string.

Parameter
variable – The index of an argument in the pattern string.
newFormat – The format object to use.

public void setFormats(Format[] newFormats);

public void setFormats(Format[] newFormats) method sets the Format objects that format the arguments of this MessageFormat. Note formats are numbered according to the order in which they appear in the formatting pattern string, not according to their specified argument numbers.

Parameter
newFormats – The format objects to use.

public void setLocale(Locale theLocale);

public void setLocale(Locale theLocale) method sets the Locale object that generates the default date, time, and number format objects.

Parameter
theLocale – The new locale.

public String toPattern();

public String toPattern() method returns the pattern string of this MessageFormat.

Apart from these methods MessageFormat class also has inherited methods from class- Object. They are as follows:

  • finalize()
  • notifyAll()
  • wait()
  • wait(long, int)
  • equals(Object)
  • getClass()
  • notify()
  • toString()
  • wait(long)

MessageFormat class also has inherited methods from Format. They are as follows:

  • format(Object)
  • parseObject(String)

This method returns the pattern string of this MessageFormat.

how to use this class?

This area also covers the message format java API.

MessageFormat is kind of Printf() function, we find in C language. MessageFormat supports the below functions:

public Object[] parse(String source, ParsePosition status);
public Object[] parse(String source) throws ParseException;
public Object parseObject(String text, ParsePosition status);

The parse() method enables us to parse an array of objects from a specified String. It is governed by the specified pattern.

public void setFormat(int variable, Format newFormat); 
public void setFormats(Format[] newFormats);

setFormat() method enables us to change the Format object in a particular position with a particular pattern.

public void applyPattern(String newPattern);

This method enables us to set a new pattern for the MessageFormat.

public String toPattern();

This method returns the current formatting pattern.

public void setLocale(Locale theLocale);

This method specifies that the MessageFormat should use a nondefault Locale. We can insert DateFormat and NumberFormat objects to format dates and numbers. We can use them for formatting the message as a pattern.

Reference:

Oracle MessageFormat

Share and Enjoy !

47 thoughts on “Class MessageFormat in Java With Example”

  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

  6. It is appropriate time to make some plans for the future and it is time to be happy.
    I’ve read this post and if I could I desire to suggest you few interesting things or suggestions.
    Perhaps you could write next articles referring to this
    article. I wish to read more things about it!

  7. Very great post. I simply stumbled upon your weblog and wanted to mention that I have
    really loved browsing your weblog posts. After all I’ll be subscribing to your rss feed and I
    hope you write again very soon!

  8. Heya i am for the first time here. I came
    across this board and I find It really useful & it helped me out much.
    I hope to give something back and aid others like you
    helped me.

  9. “I really like it whenever people come together and share ideas. Great blog, continue the good work!”

  10. Excellent site you’ve got here.. It’s difficult to find high-quality writing like
    yours these days. I truly appreciate individuals like you!
    Take care!!

  11. I’ve been exploring for a little for any high quality articles or weblog posts
    on this sort of house . Exploring in Yahoo I ultimately stumbled upon this site.
    Reading this information So i am glad to convey that I’ve
    a very good uncanny feeling I discovered exactly what I needed.

    I most without a doubt will make sure to don?t put out of your mind this web site and provides it a look on a relentless basis.

  12. What’s up friends, how is all, and what you desire to say
    concerning this piece of writing, in my view its really
    remarkable in support of me.

  13. I do not even know how I ended up here, but I thought this post was good.
    I do not know who you are but definitely you’re going to a famous blogger if you are not already 😉 Cheers!

  14. I enjoy, lead to I found just what I was having a look for.

    You have ended my four day long hunt! God Bless you man. Have a great day.
    Bye

  15. Pingback: Google

  16. Pingback: Google

  17. Pingback: Google

  18. Pingback: Google

  19. all the time i used to read smaller articles which as
    well clear their motive, and that is also happening with this paragraph which I am reading at this place.

  20. Hey just wanted to give you a quick heads up.
    The words in your article seem to be running off
    the screen in Opera. I’m not sure if this is a formatting issue or something to do with internet
    browser compatibility but I figured I’d post to let you know.
    The design look great though! Hope you get the issue resolved soon. Cheers

  21. jestine.pennefather

    An intriguing discussion is definitely worth comment.
    There’s no doubt that that you need to write more on this subject, it
    may not be a taboo matter but generally people
    do not discuss these topics. To the next! Best wishes!!
    adreamoftrains website hosting

  22. I’m gone to tell my little brother, that he should also pay a visit this website on regular basis to get updated from most up-to-date information.

  23. Pingback: Google

  24. Pingback: Google

  25. Pingback: Google

  26. Thank you for the auspicious writeup. It in fact used to be a enjoyment account it.
    Glance advanced to more added agreeable from you! However, how could we keep up a
    correspondence?

  27. Pingback: Google

  28. Pingback: Google

  29. Pingback: Google

  30. Pingback: Google

  31. Pingback: Google

  32. Pingback: Google

  33. Pingback: Google

  34. Pingback: Google

  35. Pingback: Google

  36. Pingback: Google

  37. Pingback: Google

  38. Pingback: Google

  39. Pingback: Google

  40. Pingback: Google

  41. Pingback: Google

  42. Pingback: Google

  43. Pingback: Google

Leave a Comment

Your email address will not be published. Required fields are marked *