What is a Java NumberFormatException?

Java exception FAQ: What is a Java NumberFormatException?

Solution

A Java NumberFormatException usually occurs when you try to do something like convert a String to a numeric value, like an int, float, double, long, etc. The exception indicates that the conversion process failed, such as if you try to convert a string like "foo" to an int.

NumberFormatException example

The best way to show a NumberFormatException is by example, so here’s an example where I intentionally write bad Java code to throw a NumberFormatException:

package com.devdaily.javasamples;

public class ConvertStringToNumber {

    public static void main(String[] args) {
        try {
            // intentional error
            String s = "FOOBAR";
            int i = Integer.parseInt(s);

            // this line of code will never be reached
            System.out.println("int value = " + i);
        }
        catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }
    }

}

Because there’s no way to convert the text FOOBAR into a number, trying to run this program will result in the following output:

java.lang.NumberFormatException: For input string: "FOOBAR"
   at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
   at java.lang.Integer.parseInt(Integer.java:447)
   at java.lang.Integer.parseInt(Integer.java:497)
   at com.devdaily.javasamples.ConvertStringToNumber.main(ConvertStringToNumber.java:11)

So, a NumberFormatException is an Exception that might be thrown when you try to convert a String into a number, where that number might be an int, a float, or any other Java numeric type.