You could simply do
System.out.printf("i is %02d%n", i);
Have a look at the documentation for Formatter
for details. Relevant parts are:
- The format specifiers for general, character, and numeric types have the following syntax:
%[argument_index$][flags][width][.precision]conversion
(In this particular case, you have 0
as flag, 2
as width, and d
as conversion.)
Conversion
'd'
integral The result is formatted as a decimal integer
Flags
'0'
The result will be zero-padded
This formatting syntax can be used in a few other places as well, for instance like this: String str = String.format("i is %02d", i);