Example: NumberFormatException

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

Example 1

public class NumberFormatExceptionExample1 {

  public static void main(String[] args) {
    String[] arr = new String[5];

    try {
      Integer integer = Integer.valueOf(arr[2]);
      System.out.println(integer);

    } catch (NumberFormatException e) {
      System.out.println("This is your problem:");
      System.out.println("Error: " + e);
    }
  }
}
Output
This is your problem:
Error: java.lang.NumberFormatException: null

Example 2

The parseInt() method parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits. If not, a NumberFormatException is thrown.

public class NumberFormatExceptionExample2 {

  public static void main(String[] args) {
    String str = "String";

    try {
      int number = Integer.parseInt(str);
      System.out.println(number);

    } catch (NumberFormatException e) {
      System.out.println("This is your problem:");
      System.out.println("Error: " + e);
    }
  }
}
Output
This is your problem:
Error: java.lang.NumberFormatException: For input string: "String"

Example 3

If all string arguments are integer numbers, the parseInt() method parses the string argument as a signed decimal integer.

public class ParseIntWorkingExample {

  public static void main(String[] args) {
    String str = "12345";

    try {
      int number = Integer.parseInt(str);
      System.out.println(number);

    } catch (NumberFormatException e) {
      System.out.println("This is your problem:");
      System.out.println("Error: " + e);
    }
  }
}
Output
12345