Monday, October 6, 2008

Java 5 Features - Part 1 - Formatting

I've been using Java for a long time, and one of the first comments I made about Java, when I switched from C, was "Where's printf?". Most people will never need to use printf, and in the few cases that you need to format something, you can use Java's MessageFormat class, at least that's what Java enthusiasts would have you believe.

As you may know, Java 5 introduced the printf() function. Even though I knew it was there, I still resisted using it until recently. And now, I can't imagine not having it. I don't know why I resisted using it? I used Generics as soon as it was availble, but printf() just eluded me, even though I found it to a great function in C.

I may be one of the last people that still write command line applications. I like command line applications, and a well written command line application can support a gui, if needed. But, command line applications require a lot of printing to the console screen. In java, this resulted in a lot of ugly code like

System.out.println("Unable to open File: " + file.getAbsolutePath() + " for writing. Please check permissions.");


But using printf, you can clean that up a little....
System.out.printf("Unable to open File: %s for writing. Please check permissions.", file.getAbsolutePath());


I don't suggest that you abuse the printf function, but know it's there. Also know that the String function has a static method for using printf formatting. This can be handy at times when you need to log a lot of data in a single line, or if you need to simply format a String for some reason.

For example,
log.debug(String.format("The Process: %s took %sms to run.", process, time));


or

String msg = String.format("%-20s: %s", cmd, description);


The whole printf function can do a lot of pretty complex formatting, so check it out, and the next your are printing messages to the console, just maybe you'll use printf().

No comments: