How to format message with integer fillers in Java

Java 8Object Oriented ProgrammingProgramming

To format message with integer fillers in Java, we use the MessageFormat class. The MessageFormat class gives us a way to produce concatenated messages which are not dependent on the language. The MessageFormat class extends the Serializable and Cloneable interfaces.

Declaration − The java.text.MessageFormat class is declared as follows −

public class MessageFormat extends Format

The MessageFormat.format(pattern, params) method formats the message and fills in the missing parts using the objects in the params array matching up the argument numbers and the array indices.

The format method has two arguments, a pattern and an array of arguments. The pattern contains placeholder in {} curly braces which have a index that indicate the position in the array where the value of the argument is stored and a number argument indicating that the filler is a number. They are as follows −

MessageFormat.format("{0,number} Hellos and {1,number} Worlds", obj);

Let us see a program to format the message with integer fillers −

Example

 Live Demo

import java.text.MessageFormat;
public class Example {
   public static void main(String[] args) throws Exception {
      Object[] obj = new Object[] { new Integer(23), new Integer(56) };
      String message = MessageFormat.format("{0,number} Hellos and {1,number} Worlds", obj);
      System.out.println(message);
   }
}

Output

23 Hellos and 56 Worlds

We use the format method to format the message with integer fillers as follows −

Object[] obj = new Object[] { new Integer(23), new Integer(56) };
String message = MessageFormat.format("{0,number} Hellos and {1,number} Worlds", obj);

Here, the placeholders {0,number} and {1,number} act as fillers.

raja
Published on 08-Jan-2019 07:51:53
Advertisements