What is a Java NumberFormatException?

Java exception FAQ: What is a Java NumberFormatException?

Answer: 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 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
    {
      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.

Post new comment

The content of this field is kept private and will not be shown publicly.