java.util.IllegalFormatConversionException when using System.out.format()

A few weeks ago I described how to format output using System.out.printl() and System.out.println() methods…

Try to run the code below:

double avgAge = 245 / 34;  
System.out.format("Average age is %d.", avgAge);

Without doubts you’ll get an exception thrown at runtime:

Average age is Exception in thread "main" 
d != java.lang.Double
    at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
    at java.util.Formatter$FormatSpecifier.printInteger(Unknown Source)
    at java.util.Formatter$FormatSpecifier.print(Unknown Source)
    at java.util.Formatter.format(Unknown Source)
    at Source)

The reason is becase wrong conversion label was used. To recall, conversion label is ‘%’ sign followed by a letter b, c, d, f, or s inside System.out.format().

In the above example, %d meant that an integral type (byte, Byte, short, Short, int, Integer, long, Long, BigInteger) would be used. However, finally there was a floating point passed (avgAge). This example would work if this conversion label were used: %f.

So, remember to be careful with conversion label!

Previous Post
Next Post