Data is rarely static - and thank heavens for that; if it were, not only would life be pretty boring, but I know I would be out of a job. No, typically data is very dynamic in nature - usually changing each time the user interacts with the application. Given that, it can also be deduced that messages visually presented to the user also need to be dynamic.
Most of us are familiar with string concatenation. Appending strings together is a fairly regular task I would say for the average Java developer. A lot of times I find responses to the user containing dynamic data are created in this way:
String value1 = "123456";String value2 = "asdfjk"; String output = "Value 1 equals: " + value1 + " and Value 2 equals: " + value2;System.out.println(output);// prints:// The value of value 1 is: 123456 The value of value 2 is: asdfjk
Introducing Message Format
As some of you know, however, there is a better way. The java.text.MessageFormat class and the corresponding helper classes are a relatively comprehensive API for converting a generalized 'template' message into a case-specific message with dynamic values, and all. Generally speaking, the message format API is a great way to abstract the general structure of a message from the actual content. For those of you who are already familiar with all of this, and find yourself saying 'yeah, yeah, yeah... what else is new?', I'd like to ask you hold off for the near future. I'll be covering much more complex use cases with the message format API in the near future. Today I'd like to lay some groundwork on how to use the message format class for those readers who might not be familiar.
So, as I mentioned before, message formats are all about seperating the message structure and the message content. The question to answer, then, is at a basic form, how the message format class does this? The power is in the message format template syntax. Converting the example above, here is how we would achieve the same result using java.text.MessageFormat:
Object[] values = { "123456", "asdfjk" }; String output = MessageFormat.format("Value 1 equals: {0} and Value 2 equals: {1}", values);System.out.println(output);// prints:// The value of value 1 is: 123456 The value of value 2 is: asdfjk
As you can see in the above code, the locations in the string to swap the dynamic values in are captured by a number surrounded by curly braces. In other words, {0} accounts for the 1st location in the array, {1} accounts for the 2nd location in the array, and so forth. So far, the differences between the string concatenation and this block are negligible. Here is where things get interesting, however.
MessageFormat Objects
The first thing to note is that the message format class is not just a static method as I used it above. No, in fact message formats are designed to be created for a particular format, and then reused (or even potentially be reused for multiple formats). This can be done by using the instance method






