java numberformatexception for input string code example

Example 1: 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();
        }
    }

}

Example 2: java.lang.NumberFormatException: For input string: ""

"N/A" is not an integer. It must throw NumberFormatException if you try to parse it to an integer.

Check before parsing or handle Exception properly.

Exception Handling

try{
    int i = Integer.parseInt(input);
} catch(NumberFormatException ex){ // handle your exception
    ...
}

Example 3: java.lang.NumberFormatException: For input string: "0.01""

Long.valueOf("0.01"");

Tags:

Java Example