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

The NumberFormatException is one of the most common errors in Java applications, 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 that cannot be converted into a number, there are many reasons and inputs due to which NumberFormatException occurs in Java applications.

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 for java.lang.NumberFormatException in Java programs.

Having knowledge of these causes 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 for 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 Input 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 the error message also contains the argument to parseInt(), which is null, and that's the reason for 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.



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 an 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 these Java Coding Courses for beginners 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 for 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 the parseLong() method is correctly printing the invalid input, it's hard to spot the leading or trailing error in log files, particularly the 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 the 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, particularly 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 like the parseInt() or parseFloat().



6. Null String

We've already seen a scenario where the 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" 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 these Java development courses for beginners on Medium.



7. Floating point String

This is a little bit different, even though "1.0" is a 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 for 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 the 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 these free Java programming courses 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 a weird error.



10. Similar looking characters like 1 and l

This is the close cousin of earlier error. This time also our eye believes that input String is valid and thinks that the computer has gone mad, but it wasn't. Only after spending hours did you realize that Java was right, the String you are trying to convert into a number was not numeric one "1" instead it was a small case letter L, i.e. "l". You can see it's very subtle and not obvious from the 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 a 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 a number in Java. 


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)

Also, if you get input from the user, make sure you perform validation. Use Scanner if taking input from the command line and methods like the 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.

15 comments:

  1. If i have a Object which has Long value,but i am getting NumberFormatException while object.toString() method call

    ReplyDelete
  2. int contact=Integer.parseInt(fieldcontact.getText());
    I've this code in java swing..I've taken in mysql data mobile no column i took int data type of this column which is lenth 25..i m inserting 10 digit mobile it can not be accepting..java.lang.NumberFormatException: For input string: "7977949169" getting this exception..plzz help me

    ReplyDelete
    Replies
    1. Same bro but you submit upto 9 digit easily

      Delete
    2. why can't it take 10 digits?

      Delete
    3. It may be going out of bound. Integer max value is 2147483647 which is 10 digit starting with 2 anything higher than that may not work.

      Delete
  3. u can change the int value to long,

    i think it's working fine

    ReplyDelete
  4. public static String connection() throws FileNotFoundException {
    // TODO Auto-generated method stub
    String str = new String();
    Scanner sc = new Scanner(new File("D:\\Stringfile.txt"));
    while(sc.hasNext()) {

    String str1 = sc.next();
    System.out.print(str1);
    //int n = Integer.parseInt(str);
    //System.out.println(n);
    }

    sc.close();

    return str;
    }

    public void run()
    {
    try {
    synchronized(mainthread1) {
    //for(int i=0;i<3;i++) {
    // Integer.parseInt(mainthread1.connection().getProperty("status"));
    while(Integer.parseInt(mainthread1.connection())!=1) {
    //sleep(5000);
    //System.out.println("Thread1 is waiting for some time");
    mainthread1.wait(10);
    //System.out.println("Thread1 is executing...");

    }

    System.out.println("Thread1");
    mainthread1.status = 2;
    mainthread1.notifyAll();
    System.out.println("Thread1 is executed and notifying to Thread2");
    sleep(1000);
    }
    //}
    }catch (Exception e) {
    System.out.println(e);
    }
    }
    }

    ReplyDelete
    Replies
    1. Hello madhu, what is the problem?

      Delete
    2. Exception java lang number format exception. For input string this page is always coming when I am updating my profile in college website

      Delete
  5. I am having NumberFormatException after converting numeric values in Java swing





    ReplyDelete
    Replies
    1. Can you post your code? may be we can check, it's journally a string which cannot be parsed.

      Delete
  6. Hello, here my code


    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;

    public class CityGraph {

    ArrayList vertexes = new ArrayList<>() ;


    ArrayList readInput(String filePath) throws IOException {

    ArrayList adjMatrix;
    adjMatrix = new ArrayList<>();
    String [] arrOfStr;
    long x,y;

    String temp;
    BufferedReader br = new BufferedReader(new FileReader(filePath));

    while ((temp = br.readLine()) != null) {
    arrOfStr = temp.split(" ",3);
    x = Long.parseLong(arrOfStr[1]);
    y = Long.parseLong(arrOfStr[2]);
    adjMatrix.add(new CityVertex(x,y));
    }
    return adjMatrix;
    }

    void distance(ArrayList adjMatrix){
    int i,j;
    long x,y,sq1,sq2;
    for (i=0; i<adjMatrix.size();i++){
    x = adjMatrix.get(i).x;
    y = adjMatrix.get(i).y;
    for (j=0; j<adjMatrix.size();j++){
    sq1 = (x-adjMatrix.get(j).x)*(x-adjMatrix.get(j).x);
    sq2 = (y-adjMatrix.get(j).y)*(y-adjMatrix.get(j).y);
    adjMatrix.get(i).edges.add( j,Math.round((float)(Math.sqrt(sq1 + sq2))));
    }
    }

    }
    }

    and this is error

    Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
    at java.base/java.lang.Long.parseLong(Long.java:717)
    at java.base/java.lang.Long.parseLong(Long.java:832)
    at CityGraph.readInput(CityGraph.java:24)
    at main.main(main.java:20)

    ReplyDelete
    Replies
    1. I think you are passing empty string from File

      Delete

Feel free to comment, ask questions if you have any doubt.