java.lang.NumberFormatException

In this post, we will see about Java.lang.NumberFormatException.

java.lang.NumberFormatException occurs where you try to convert any non-numeric String to Number such as Integer, Double, Float or Long.

This exception generally occurs when you get input from user in the form of String. This is not Java developer‘s fault and mostly data error. In this scenario, data should be corrected and you can log the error to log file for analysis later. If you do not handle the application then the application might crash.

Let’s understand it with the help of an example.

When you run above program, you will get below output:

Iteration 1: Put correct Integer value

Please enter a number:
10
Converted int value = 10

Iteration 2: Put NA as user input

Please enter a number:
NA
java.lang.NumberFormatException: For input string: “NA”
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at org.arpit.java2blog.StringToIntegerConversion.main(StringToIntegerConversion.java:14)

As "NA" can not be converted to Integer, it will throw above exception.

Iteration 3: Put “” as user input

Please enter a number:
java.lang.NumberFormatException: For input string: “”
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at org.arpit.java2blog.StringToIntegerConversion.main(StringToIntegerConversion.java:14)

As "" can not be converted to Integer, it will throw above exception.

Iteration 4: Put “1.0” as user input

Please enter a number:
1.0
java.lang.NumberFormatException: For input string: “1.0”
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at org.arpit.java2blog.StringToIntegerConversion.main(StringToIntegerConversion.java:14)

It is also necessay that given input string should be able to convert to target data type as "1.0" can not be converted to Integer.


How to resolve java.lang.NumberFormatException

If you are getting java.lang.NumberFormatException, you can easily find information in exception itself.

For example:

java.lang.NumberFormatException: For input string: “NA”

As NA is alphanumeric and can not be converted to Integer.

Only way to avoid this exception is correct the input data and you should put proper exception handling whenever you are doing String to Number conversion.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *