Java MessageFormat Class

Profile picture for user arilio666

The Java MessageFormat class is a utility class that provides a way to format strings that contain placeholders for dynamic values.  It is a part of Java.text package is used for creating strings with placeholders and then filling those placeholders with dynamic data at runtime.

format() method in Java.text.MessageFormat gets the formatted array of objects appended into a string buffer object. To create a formatted message using MessageFormat, you first create an instance of the class by passing the format string as a parameter to the constructor. 

You can then call the format method of the MessageFormat object, passing in the values that should replace the placeholders in the format string.

    String format = "Hello {0}, are you {1}";
        MessageFormat messageFormat = new MessageFormat(format);
        Object[] values = { "John," "Ready!!" };
        String formattedMessage = messageFormat.format(values);
        System.out.println(formattedMessage);
        
  • Here we used a format string with two placeholders {0} and {1}, then with Java.text utility, we created a 
  • MessageFormatobject with the format string.
  • We then immediately create an array of values for the placeholders to replace with.
  • Then we use the MessageFormat object and the format to replace the placeholder values with the array values.
  • So here is the result of the operation
Tags