NumberFormatException in Java Example

This Java example demonstrates the usage of java.lang.NumberFormatException class with an example. This NumberFormatException occurs when a string is parsed to any numeric variable.
From JavaDoc - The NumberFormatException exception 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.

NumberFormatException Class Diagram


Java NumberFormatException Example

In the below example, we are trying to parse "100ABCD" string into integer leads to NumberFormatException:
package com.javaguides.corejava;

public class NumberFormatExceptionExample {

    public static void main(String[] args) {

        String str1 = "100ABCD";
        try {
            int x = Integer.parseInt(str1); // Converting string with inappropriate format
            int y = Integer.valueOf(str1);
        } catch (NumberFormatException e) {
            System.err.println("NumberFormatException caught!");
            e.printStackTrace();
        }
    }
}
Output:
NumberFormatException caught!
java.lang.NumberFormatException: For input string: "100ABCD"
 at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
 at java.lang.Integer.parseInt(Integer.java:580)
 at java.lang.Integer.parseInt(Integer.java:615)
 at com.javaguides.corejava.NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:9)

Reference

Comments