Last editor: Dave Cherry, last modified: Oct 25, 2009
java.util.Formatter and String.format(..) were introduced in Java 1.5. These provide functionality similar to printf in C++ (actually a bit more like sprintf). We will always use String.format in this example. For those familiar with printf, you can skip the next paragraph.
Using printf for formatting in C made some tasks very simple, hence why its made a comeback several years later in Java. Many of the runtime disadvantages associated with printf in C do not have the same consequences in Java. For example parameter mismatch was a serious problem in C, but in Java can be handled via an exception. However, one disadvantage of using this is that the String must be parsed each time the method is called.
Format works by parsing the format string (first parameter), and for each escape (%<type>) found, it replaces the escape with the next parameter. If there are too few parameters an exception is thrown. Each escape is made up of the % character followed by type information (and optionally a formatting specification). For simple escapes, 's' is a String, 'd' is an integer and 'f' is floating point. Without further delay, lets take a look:
public class Formatting
{
public static void main(String[] args)
{
int iVal = 10;
long lVal = 30;
double dVal = 3.5;
// simple example just print an integer, double and long.
String simpleFmt = String.format("Values: %d %f %d", iVal, dVal, lVal);
System.out.println(simpleFmt);
// Complex formatting example using same variables as above
// %04d - integer with 4 places zero padded.
// %.2f - floating point to two decimal places after point.
// %9d - integer padded to 9 places not zero padded.
String specificFmt = String.format("Values: %04d %.2f %9d", iVal, dVal, lVal);
System.out.println(specificFmt);
}
}
Output:
Values: 10 3.500000 30
Values: 0010 3.50 30 Notice that the line of first output does not contain any padding, and the floating point value is to 6 places of precision; these are the defaults when using format. However, the second line is somewhat different, notice the zero padding and space padding of the first and last item. Also note that the floating point value is to a lesser precision.
Next page: NumberFormat, last page DateFormat.