Close

IllegalFormatFlagsException: Using invalid padding specifier for integers

Java Exceptions Java API 


Class:

java.util.IllegalFormatFlagsException

java.lang.Objectjava.lang.Objectjava.lang.Throwablejava.lang.Throwablejava.io.SerializableSerializablejava.lang.Exceptionjava.lang.Exceptionjava.lang.RuntimeExceptionjava.lang.RuntimeExceptionjava.lang.IllegalArgumentExceptionjava.lang.IllegalArgumentExceptionjava.util.IllegalFormatExceptionjava.util.IllegalFormatExceptionjava.util.IllegalFormatFlagsExceptionjava.util.IllegalFormatFlagsExceptionLogicBig

Cause of the exception

This error can occur when we try to use negative sign with zero padding specifier %0Nd where N can be any integer.

package com.logicbig.example.illegalformatflagsexception;

public class IllegalFormatFlagsExceptionRightZeroPadding {
public static void main(String[] args) {
//right zero padding for integers not possible
System.out.printf("%0-5d", 21);
}
}

Output

java.util.IllegalFormatFlagsException: Flags = '-0'
at java.util.Formatter$FormatSpecifier.checkNumeric (Formatter.java:3181)
at java.util.Formatter$FormatSpecifier.checkInteger (Formatter.java:3136)
at java.util.Formatter$FormatSpecifier.<init> (Formatter.java:2874)
at java.util.Formatter.parse (Formatter.java:2713)
at java.util.Formatter.format (Formatter.java:2655)
at java.io.PrintStream.format (PrintStream.java:1209)
at java.io.PrintStream.printf (PrintStream.java:1105)
at com.logicbig.example.illegalformatflagsexception.IllegalFormatFlagsExceptionRightZeroPadding.main (IllegalFormatFlagsExceptionRightZeroPadding.java:13)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:564)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:282)
at java.lang.Thread.run (Thread.java:832)




Avoiding the exception

Avoid using negative sign for integer zero padding

package com.logicbig.example.illegalformatflagsexception;

public class IllegalFormatFlagsExceptionRightZeroPaddingFix {

public static void main(String[] args) {
//right zero padding for integers not possible
System.out.printf("%05d", 21);
}
}

Output

00021




See Also