Substitute tokens in a String in Java

Java 8Object Oriented ProgrammingProgramming

To substitute tokens in a String in Java, we use the Message Format class. The Message Format class provides a means to produce concatenated messages which are not dependent on the language. The Message Format 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 brace which indicate the position in the array where the value of the argument is stored.

Let us see an example to substitute tokens in Java −


 Live Demo

import java.text.MessageFormat;
public class Example {
   public static void main(String[] args) {
      Object[] obj = new Object[] { "Good", "!!"};
      // The Morning argument has the placeholders 0 and 1 so it lies between Good and !!
      // Thus it substitutes !! token with Morning token
      System.out.println(MessageFormat.format("{0} Morning {1}", obj));


Good Morning !!
Published on 08-Jan-2019 07:48:35