Monday, April 14, 2008

printf (sprintf) in Java

Do you know this feeling that you need some very-very common functionality, which has to be implemented dozens of times and you still has no idea how to do it in Java?

One great example is "printf" or "sprintf" function from C. Almost everyone, who starts learning C, develops "Hello Word" application using printf.
And what happens when you move from C to Java? "There is no printf", I was told, when I started to learn Java, "but you don't really need it. User StringBuffers (StringBuilder since Java 5) to build strings and it will work just fine in most cases." And that what I did. And I have really got used to it.

And surprise! Since Java 5 there is "printf" in Java. As everything in Java it's a class and it's called Formatter (java.util.Formatter).
You can read the Java Doc to see how to use it, but there is a shortcut for sprintf: The class String now contains two methods format(String format, Object ... args) and format(Locale l, String format, Object ... args) that work almost exactly like sprintf.

Personally I'm feeling really ashamed that it took me two years of using Java 5 to discover this functionality.

No comments: