Blog |

How to Fix The Format Flags Conversion Mismatch Exception in Java

How to Fix The Format Flags Conversion Mismatch Exception in Java
Table of Contents

A FormatFlagsConversionMismatchException is an unchecked runtime exception which is thrown when a conversion and a flag are incompatible in the source code. This is a very common exception encountered when the programmer tries to format the string. Unless otherwise specified, passing a null argument to any method or constructor in this class will cause a NullPointerException to be thrown.

 

Here is the syntax of a FormatFlagsConversionMismatchException:

public class FormatFlagsConversionMismatchException: IllegalFormatException

Here is the hierarchy of the FormatFlagsConversionMismatchException class:

Object -> Throwable -> Exception -> RuntimeException -> IllegalArgumentException -> IllegalFormatException -> FormatFlagsConversionMismatchException

 

When does FormatFlagsConversionMismatchException occur in Java?

The FormatFlagsConversionMismatchException class has a constructor that constructs an instance of this class with the specified flag ( f ) and conversion ( c ). So whenever there is an incompatibility between the flag and the conversion, this exception is thrown.

public FormatFlagsConversionMismatchException(String f, char c)

Example one: Formatting the String Using String.format()

A common scenario where many programmers encounter this exception is while formatting the string using the String.format() method.

public class Demo {

  public static void main(String[] args) {
    int n = 3;
    String str = "Tony stark";
    int noOfSpaces = n * 2;
    noOfSpaces = str.length() + noOfSpaces;
    String output = String.format("%1$#" + noOfSpaces + "s", str);

    System.out.println(output);

  }
}

The flag # can only be applied to %o, %x, %f, and %e format specifiers only, but here it is %s. And as the # flag and the given argument are not compatible or formattable with the conversion s(string), FormatFlagsConversionMismatchException is thrown.

Output of Example One

Exception in thread "main" java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags = #
    at java.base/java.util.Formatter$FormatSpecifier.failMismatch(Formatter.java:4438)
    at java.base/java.util.Formatter$FormatSpecifier.printString(Formatter.java:3052)
    at java.base/java.util.Formatter$FormatSpecifier.print(Formatter.java:2933)
    at java.base/java.util.Formatter.format(Formatter.java:2695)
    at java.base/java.util.Formatter.format(Formatter.java:2625)
    at java.base/java.lang.String.format(String.java:4140)
    at com.example.myJavaProject.Demo.main(Demo.java:15)

 

Example Two: Forgetting to Escape % in System.out.printf() Statement

The printf() method is used in the below example. The printf() method belongs to the Java PrintStream class. It is a common way to write a string which is formatted for this output stream. It uses the specified format string and arguments. In the printf() statement, we haven’t escaped the % (percent) in the printf(), which causes the FormatFlagsConversionMismatchException.

public class Demo {

  public static void main(String[] args) {

    double salesTax = 84.3455;
    double total = (8.265 * salesTax) / 100;
    System.out.printf("8.265% Sales tax %.2f\n        ", total);

  }
}

Output of Example Two

Exception in thread "main" java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags =  
    at java.base/java.util.Formatter$FormatSpecifier.failMismatch(Formatter.java:4438)
    at java.base/java.util.Formatter$FormatSpecifier.checkBadFlags(Formatter.java:3176)
    at java.base/java.util.Formatter$FormatSpecifier.checkGeneral(Formatter.java:3134)
    at java.base/java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2896)
    at java.base/java.util.Formatter.parse(Formatter.java:2747)
    at java.base/java.util.Formatter.format(Formatter.java:2671)
    at java.base/java.io.PrintStream.format(PrintStream.java:1209)
    at java.base/java.io.PrintStream.printf(PrintStream.java:1105)
    at com.example.myJavaProject.Demo.main(Demo.java:14)

 

Handling FormatFlagsConversionMismatchException in Java

Now let’s see how to debug and handle this exception in Java. The best approach is to use try-catch blocks and to be a little careful when formatting String values. Let’s fix both the examples discussed above.

Fixing Example One

On observing the first few lines of the output, it is evident that this exception occurred because of the flag and the conversion not being compatible, which is caused by the # flag, which is not compatible with %s in the String.format() method.

Exception in thread "main" java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags = #
    at java.base/java.util.Formatter$FormatSpecifier.failMismatch(Formatter.java:4438)
    at java.base/java.util.Formatter$FormatSpecifier.printString(Formatter.java:3052)
    at java.base/java.util.Formatter$FormatSpecifier.print(Formatter.java:2933)
    at java.base/java.util.Formatter.format(Formatter.java:2695)
    at java.base/java.util.Formatter.format(Formatter.java:2625)
    at java.base/java.lang.String.format(String.java:4140)
    at com.example.myJavaProject.Demo.main(Demo.java:15)

Resolved Code For Example One

The block of code can be fixed by removing # flag as it is not compatible with %s and the try-catch block can also be used with it.

public class Demo {

  public static void main(String[] args) {
    try {
      int n = 20;
      String str = "Tony stark";
      int noOfSpaces = n * 2;
      noOfSpaces = str.length() + noOfSpaces;
      String output = String.format("%1$" + noOfSpaces + "s", str);

      System.out.println(output);

    } catch (Exception e) {
      System.out.println("Exception has occurred");
    }
  }
}

Output

The string is printed after 20*2 = 40 whitespaces

                                       Tony stark

 

Fixing Example Two

Exception in thread "main" java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags =  
    at java.base/java.util.Formatter$FormatSpecifier.failMismatch(Formatter.java:4438)
    at java.base/java.util.Formatter$FormatSpecifier.checkBadFlags(Formatter.java:3176)
    at java.base/java.util.Formatter$FormatSpecifier.checkGeneral(Formatter.java:3134)

Analyzing the result makes it obvious that the flag component is empty and that java.util.Formatter is to blame for the issue. This is so that printf() may interpret the format string and produce output using the java.util.Formatter class. And failure to escape the character that is generating this issue while printing the percentage (%) in the printf() statement's output.

Resolved Code For Example Two

The code can be fixed by escaping % by adding one % before it => %%, and we also add try-catch blocks with it.

public class Demo {

  public static void main(String[] args) {

    try {
      double salesTax = 84.3455;
      double total = (8.265 * salesTax) / 100;
      System.out.printf("8.265%% Sales tax %.2f\n        ", total);

    } catch (Exception e) {
      System.out.println("An exception has occurred");
    }
  }
}

Output

8.265% Sales tax 6.97

 

Avoiding FormatFlagsConversionMismatchException in Java

Finally, we can conclude that FormatFlagsConversionMismatchException occurs when there is no compatibility between the flag and the conversion.

Since this happens frequently when formatting strings, it's best practice to put the string formatting portion of the code inside of a try-catch block.

Additionally, it's a good idea to precisely follow the syntax of string formatting methods and escape any essential characters. As a workaround, developers can also use other methods to format which are present in the StringBuilder class.

 

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape