10 Reasons of java.lang.NumberFormatException in Java - Solution

The NumberFormatException is one of the most common errors in Java application along with NullPointerException. This error comes when you try to convert a String into numeric data types e.g. int, float, double, long, short, char or byte. The data type conversion methods like Integer.parseInt(), Float.parseFloat(), Double.parseDoulbe(), and Long.parseLong() throws NumberFormatException to signal that input String is not valid numeric value. Even though the root cause is always something which cannot be converted into a number, there are many reasons and input due to which NumberFormatException occurs in Java application. Most of the time I have faced this error while converting a String to int or Integer in Java, but there are other scenarios as well when this error occurs. In this article, I am sharing 10 of the most common reasons of java.lang.NumberFormatException in Java programs.

Having knowledge of these cause will help you to understand, analyze and solve this error in your Java application. In each case, you'll see an error message and then I'll explain the reason behind it. It's difficult to cover all scenarios on which JVM throws this error but I have tried to capture as many as possible here. If you find any other reasons or faced this error in your Java project due to anything mentioned below then please share with us via comments.




10 common reasons of NumberFormatException 

Here are 10 reasons which I have seen causing NumberFormatException in Java application. If you have any reason which is not listed here but you have seen them causing this error, feel free to add it.


1. Null Value
Since String is an object, it's possible that it could be null and if you pass a null String to a method like parseInt(), it will throw NumberFormatException because null is not numeric.

Integer.parseInt(null);
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:454)
at java.lang.Integer.parseInt(Integer.java:527)

You can see that error message also contains the argument to parseInt() which is null and that's the reason of this error. Thanks to JDK developers for printing the argument as well and a lesson to all Java developers who create their custom Exception class, always print the input which failed the process.  If you want to learn more about best practices, read Java Coding Guidelines.

How to solve java.lang.NumberFormatException in Java



2. Empty String
Another common reason of java.lang.NumberFormatException is an empty String value. Many developers think empty String is OK and parseInt() will return zero or something, but that's not true. The parseInt(), or parseFloat() both will throw NumberFormat error as shown below:

Integer.parseInt("");
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)

Again you can see that this method has printed the input, which is empty String and which caused the failure.


3. Alphanumeric Input
Another common reason for NumberFormatException is the alphanumeric input. No non-numeric letter other than + and - is not permitted in the input string.

Short.parseShort("A1");
Exception in thread "main" java.lang.NumberFormatException: For input string: "A1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Short.parseShort(Short.java:117)
at java.lang.Short.parseShort(Short.java:143)

You can see that our input contains "A" which is not permitted, hence it caused the error, but you should remember that A is a valid letter when you convert String to an integer in hexadecimal base. See Java: How to Program by Dietel and Dietel to learn more about data type conversion in Java.



4. Leading space
You won't believe but leading and trailing spaces are one of the major reasons of NumberFormatException in Java, you will think that input String " 123" is Ok but it's not. It has a leading space in it.

Long.parseLong(" 123");
Exception in thread "main" java.lang.NumberFormatException: For input string: " 123"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:430)
at java.lang.Long.parseLong(Long.java:483)

Even though parseLong() method is correctly printing the invalid input, it's hard to spot the leading or trailing error in log files, particularly trailing one. So, pay special attention to leading and trailing space while converting String to long in Java, if possible use trim() before passing String to parseLong() method.


5. Trailing space
Similar to above issue, trailing space is another main reason for numerous NumberFormatException in Java. A trailing white space is harder to spot than a leading white space, particular in log files.

Long.parseLong("1001 ");
Exception in thread "main" java.lang.NumberFormatException: For input string: "1001 "
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:441)
at java.lang.Long.parseLong(Long.java:483)

To avoid this error you should trim() the input String before passing it to parse methods e.g. parseInt() or parseFloat().



6. Null String
We'have already seen a scenario where parseInt() method throws NumberFormatException if the input is null, but sometimes you will see an error message like Exception in thread "main" java.lang.NumberFormatException: "null", this is different than the first scenario. In the first case, we have a null value, here we have a "null" String i.e. an initialized String object whose value is "null". Since this is also not numeric, parseInt(), or parseFloat() will throw the NumberFormat exception as shown below.

Float.parseFloat("null");
Exception in thread "main" java.lang.NumberFormatException: For input string: "null"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1250)
at java.lang.Float.parseFloat(Float.java:452)

If you are not familiar with the concept of null in Java, please see Core Java Volume 1 - Fundamentals by Cay S. Horstmann to learn more.



7. Floating point String
This is little bit different, even though "1.0" is perfectly valid String i.e. it doesn't contain any alphanumeric String but if you try to convert it into integer values using parseInt(), parseShort(), or parseByte() it will throw NumberFormatException because "1.0" is a floating point value and cannot be converted into integral one. These methods don't cast they just do the conversion.

Long.parseLong("1.0");
Exception in thread "main" java.lang.NumberFormatException: For input string: "1.0"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:441)
at java.lang.Long.parseLong(Long.java:483)

So, be careful while converting floating point String to numbers, they can only be converted to float or double, but not on integral types like byte, short, or int.



8. Out of range value
Another rare reason of java.lang.NumberFormatException is out-of-range value. For example, if you try to convert String "129" to a byte value it will throw NumberFormatException because maximum positive number byte can represent is 127. Clearly, 129 is out-of-range for a byte variable

Byte.parseByte("129");
Exception in thread "main" java.lang.NumberFormatException: Value out of range. Value:"129" Radix:10
at java.lang.Byte.parseByte(Byte.java:150)
at java.lang.Byte.parseByte(Byte.java:174)

If you are not familiar with data types and their range in Java, please see Core Java for the Impatient for more information.



9. Non-printable character
While working in the software industry, sometimes you face an issue where you think the computer is wrong, it has gone mad, the input String looks perfectly OK but still Java is throwing NumberFormatException, this happens but at the end, you will realize that computer is always right.

For example, consider this error message:
java.lang.NumberFormatException: For input string: "1"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)

"1" is perfectly Ok for parseInt() and it will run fine then why java.lang.NumberFormatException? It turns out that there was a non-printable character in front of 1 which was not displaying in the place where you are seeing. So, watch out for the non-printable character if you are facing weird error.



10. Similar characters e.g 1 and l
This is the close cousin of earlier error, this time also our eye believes that input String is valid and think that computer has gone mad, but it wasn't. Only after spending hours you realize that Java was right, the String you are trying to convert into number was not numeric one "1" instead it was small case letter L i.e. "l". You can see it's very subtle and not obvious from naked eye unless you are really paying attention.

Integer.parseInt("l");
Exception in thread "main" java.lang.NumberFormatException: For input string: "l"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)


From the error message, it looks like the error is for numeric String "1". So be careful with this.

Here is the nice slide to combine all these reasons into one, which you can share as well :

10 Reasons of java.lang.NumberFormatException in Java  - Solution


That's all about 10 common reasons of java.lang.NumberFormatException and how to solve them. It's one of those errors where you need to investigate more about data than code. You need to find the source of invalid data and correct it. In code, just make sure you catch the NumberFormatException whenever you convert a String to number in Java. Also, if you get input from the user, make sure you perform validation. Use Scanner if taking input from command line and methods like nextInt() to directly read integer instead of reading String and then parsing it to int again using parseInt() method, only to be greeted by NumberFormatExcpetion.


Other Java troubleshooting tutorials you may like to explore
  • How to fix "Error: Could not find or load main class" in Eclipse? (guide)
  • How to avoid ConcurrentModificationException in Java? (tutorial)
  • How to solve "could not create the Java virtual machine" error in Java? (solution)
  • How to fix "illegal start of expression" compile time error in Java? (tutorial)
  • Fixing java.lang.unsupportedclassversionerror unsupported major.minor version 50.0 (solution)
  • Cause and solution of "class, interface, or enum expected" compiler error in Java? (fix)
  • java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory error (solution)
  • How to solve java.lang.ClassNotFoundException: com.mysql.jdbc.Driver error? (hint)
  • How to solve java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver? (solution)
  • Common reasons of java.lang.ArrayIndexOutOfBoundsException in Java? (solution)
  • java.lang.ClassNotFoundException : org.Springframework.Web.Context.ContextLoaderListener (solution)
  • How to solve "variable might not have initialized" compile time error in Java? (answer)
  • How to fix 'javac' is not recognized as an internal or external command (solution)
  • How to fix Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger (solution)
  • How to solve java.lang.OutOfMemoryError: Java Heap Space in Eclipse, Tomcat? (solution)


References
NumberFormatException in Java SE 8



No comments:

Post a Comment