
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Substitute Tokens in a String in Java
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 −
Example
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)); } }
Output
Good Morning !!