Top 3 Java Text Formatting examples : MessageFormat

Why MessageFormat is introduced:-

I18n MessageFormat in javaBefore MessageFormat is introduced, we used to process the messages using String concatenation,
the disadvantages with String class processing is Strings are immutable objects, more objects are created in heap memory
and these messages order is not same for every language, because of this problems,
Sun has introduced text format classes like MessageFormat

String stringText="Hi"+ name+ "How are u";  

MessageFormat is class in java.text package, introduced in java 5 language, and this text format class in java used to provide capabilities for Internalization.

java.util.MessageFormat class provides capabilities to display localization specific message and format the messages as per language specific.In Any application, messages are displayed to users when validation fails or request is submitted successfully.In real world programs, messages are stored in resource bundles or property files, prorgrams read the properties files based on language.

Basic example or usage of MessageFormat

Object userInformation={"John","success"};  
String messageText=" user {username} data is submitted with {status} message";  
MessageFormat messageFormatExample=new MessageFormat(messageText);  
and output is user John data is submitted with success message  

In above code, format() method formats strings by receiving {0},{1} arguments and MessageFormat is easy to learn and implement

How to format text message contains Date fields**

MessageFormat also process which contains Date and currency fields, For this we have to specify the date format placeholders as below

Date currentDate = new Date();  
System.out.println(MessageFormat.format("Current Date is {0,date yyyy-MM-dd}", date));  
and output is Current Date is 2013-05-03  

How to format text message contains number fields:-

Numbers in messages are formatted using {0,number,000.000} which display the numbers with 3 decimals

System.out.println(MessageFormat.format("Number is  {0,number,000.000}", 123456));  
and output is Number is 123.456  

Similar Posts