MessageFormat

Java MessageFormat Example

In this example we will discuss about MessageFormat class and how to use it to write messages. MessageFormat takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.

MessageFormat extends the Format class, which is an abstract base class for formatting locale-sensitive information such as dates, messages, and numbers. It defines the programming interface for formatting locale-sensitive objects into Strings (the format() method) and for parsing Strings back into objects (the parseObject() method).

The MessageFormat class exists since JDK1.4.

The structure of MessageFormat

Constructor:

  • MessageFormat(String pattern)

    Constructs a MessageFormat for the default locale and the specified pattern.

  • MessageFormat(String pattern, Locale locale)

    Constructs a MessageFormat for the specified locale and pattern.

From Objects to Strings

To show a basic usage of MessageFormat, create a class called BasicMessageFormatExample with this source code:

BasicMessageFormatExample.java

package com.javacodegeeks.examples;

import java.text.MessageFormat;
import java.util.Date;
import java.util.Random;

public class BasicMessageFormatExample {
	
	public static boolean isPrime(int n) {
		if (n == 2) return true;
		
		for(int i=2;i<=(int)Math.sqrt(n)+1;i++) 
			if(n%i == 0) 
				return false;
	    
		return true;
	}

	public static void main(String[] args) {
	
		int[] nums = new int[10];
		Random rnd = new Random();
		
		for (int i=0;i<nums.length;i++) {
			nums[i] = rnd.nextInt(100);
		}
		
		int primes = 0;
		
		for (int num : nums) {
			if (isPrime(num)) primes++;
		}
		
		String message = "On the test run at {0,time} on {0,date}, we found {1} prime numbers";
		MessageFormat mf = new MessageFormat(message);
		
		System.out.println(mf.format(new Object[] {new Date(), primes}));

	}

}

In this example, I created an array of integers, using a Random instance as the random integer generator. Next, I tested the primality of each one of the random numbers and measured the number of them.

On line 35, I created a MessageFormat instance, giving a message pattern as argument.
Then, I used the format() method, inherited from the Format class, to show the message. This method gets an array of objects as argument.

The output would be this:

On the test run at 1:12:13 PM on Sep 2, 2014, we found 2 prime numbers

Now let’s analyze the string pattern. It is "On the test run at {0,time} on {0,date}, we found {1} prime numbers". You may notice the usage of {0,time}, which will get replaced by the today date. The numbers between brackets { } are actually indexes of the objects passed as arguments of the format() method. So, when using {0} we refer to the object whose index is 0 on that array of objects (in our case, new Date()), when using {1} we refer to the object with index 1, and so on. The other one, the string between the brackets (time) is called FormatType, and they are used to extract some information from the objects passed to the format() method.

From Strings to Objects

In the above example, we created a String by using properties of some objects. MessageFormat class allows the opposite action too, that of creating objects from message strings.

To see this, create a class called ObjectsFromStringsExample with this source code:

ObjectsFromStringsExample.java

package com.javacodegeeks.examples;

import java.text.MessageFormat;
import java.text.ParsePosition;

public class ObjectsFromStringsExample {
	public static void main(String[] args) {
		
		MessageFormat mf = new MessageFormat("String: {0}\nInteger: {1}\nDouble: {2}");
		
		Object[] objArray = {"This is a string",new Integer(56), new Double(12.34)};
		String message = mf.format(objArray);
		
		System.out.println("The message: \n"+message);
		
		Object[] obj = mf.parse(message, new ParsePosition(0));
		
		System.out.println("\n\nObjects parsed:");
		for (Object o : obj)
			System.out.println(o + " of "+o.getClass().toString());
	}
}

In this program I firstly created a message with a String, an Integer and a Double. Then, I used the parse() method to get all the objects from the message.

The output of this code is this:

The message: 
String: This is a string
Integer: 56
Double: 12.34


Objects parsed:
This is a string of class java.lang.String
56 of class java.lang.String
12.34 of class java.lang.String

More about MessageFormat

MessageFormat differs from the other Format classes in that you create a MessageFormat object with one of its constructors (not with a getInstance() style factory method). The factory methods aren’t necessary because MessageFormat itself doesn’t implement locale specific behavior. Any locale specific behavior is defined by the pattern that you provide as well as the subformats used for inserted arguments.

MessageFormat uses some format patterns and styles which you can read in the online documentation of java.text.MessageFormat

Download Code

Download
You can download the full source code of this example here : MessageFormatExample

Aldo Ziflaj

Aldo is a student of Computer Engineering and a programming addict. He spares his free time coding, whether mobile, web, or desktop programming. He is also one of the co-founders of Things Lab.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button