Presents your JAVA E-NEWSLETTER for November 4, 2002 <-------------------------------------------> CONTROL OUTPUT WITH MESSAGEFORMAT Printf was a favorite tool that many C programmers sorely missed when they moved to Java. Java had a replacement method, but it did not follow the same concepts as the printf() function in C. Fortunately, the early Java library developers had seen fit to create a tool that suited Java better than a printf function. MessageFormat allows a developer to control the formatting of variables in output text. It is a powerful class, as the following example shows: String message = "Once upon a time ({1,date}, around about {1,time,short}), there " + "was a humble developer named Geppetto who slaved for " + "{0,number,integer} days with {2,number,percent} complete user " + "requirements. "; Object[ ] variables = new Object[ ] { new Integer(4), new Date( ), new Double(0.21) } String output = MessageFormat.format( message, variables ); System.out.println(output); Hidden in the message is a little language that describes the formatting of the output. An example output is shown below: Once upon a time (Nov 3, 2002, around about 1:35 AM), there was a humble developer named Geppetto who slaved for 4 days with 21% complete user requirements. If the same message wants to be pushed out again and again with different variables, then a MessageFormat object can be built and given the message. Here's a modification of the above example: // String output = MessageFormat.format( message, variables ); // becomes: MessageFormat formatter = new MessageFormat(message); String output = formatter.format(variables); In addition to handling dates, times, numbers, and percentages, MessageFormat also deals with currencies, allows more control over the number format, and allows ChoiceFormats to be specified. MessageFormat is a neat class that probably doesn't get used as often as it should. Its biggest drawback is in wanting data to be passed in as a variable and not as a Properties object. One simple way to solve this would be a wrapper that preparsed the String to be formatted, turning the Properties key into an array index, for the ordering that Properties.keys( ) returns. ----------------------------------------