Saturday, July 17, 2021

java.lang.numberformatexception for input string null - Cause and Solution

The java.lang.NumberFormatException comes when you try to parse a non-numeric String to a Number like Short, Integer, Float, Double etc. For example, if you try to convert . "null" to an integer then you will get NumberFormatException. The error "Exception in thread "main" java.lang.NumberFormatException: For input string: "null" is specifically saying that the String you receive for parsing is not numeric and it's true, "null" is not numeric. Many Java methods which convert String to numeric type like Integer.parseInt() which convert String to int, Double.parseDoble() which convert String to double, and Long.parseLong() which convert String to long throws NumberFormatException to inform that the input String is not numeric.

By the way, this is not the application developer's fault. This is a data error and to solve this problem you need to correct the data. There could be nothing wrong with in code if you are catching this error and printing this in the log file for data analysis.

By the way, if you are not handling this exception then your application can crash, which is not good on the Java developer's part. See these free Java courses to learn more about error and exception handling in Java.

In this article, I'll show you an example of an Exception in thread "main" java.lang.NumberFormatException: For input string: "null" by creating a sample program and tell you the technique to avoid NumberFormatExcpetion in Java.




Java Program to demonstrate NumberFormatException

This is a sample Java program to demonstrate when a NumberFormatException comes. Once you go through the examples, you can reason about it. It's pretty much common sense like a null cannot be converted to a number so you will NumberFormatException. The same is true for an empty String or a non-numeric String.

One of the variants of this is a user entering a number but not in a given format like you expect an integer but the user enters "1.0" which is a floating-point literal. If you try to convert this String to Integer, you will NumberFormatException. 

If you are new to Java and want to learn more about how to convert one data type to another using the valueOf(), toString(), and parseXX() method, please see join these online Java Programming courses to learn Java in more guided and structure way. 

Here is our Java program to show different scenarios where you may encounter NumberFormatException in Java:

import java.util.Scanner;

/*
 * Java Program to solve NumberFormatException
 * The NumberFormatException is thrown by methods
 * which convert String to numeric data e.g. 
 * Integer.valueOf(), Float.valueOf(), or Double.valueOf()
 * if given input is non-numeric. 
 * 
 */

public class NumberFormatExceptionDemo {

  public static void main(String[] args) {

    System.out
        .println("Welcome to Java program to solve NumberFormatException");
    System.out
        .println("In this program we'll try to parse String to integer and see"
            + "when NumbeFormatException occurs");

    System.out.println("Please enter a number");
    Scanner scnr = new Scanner(System.in);
    String input = scnr.nextLine();

    int number = Integer.parseInt(input);

    System.out.println("The converted integer is " + number);
    scnr.close();
  }

}

Output
Welcome to Java program to solve NumberFormatException
In this program, we will try to parse String to integer 
and see when NumbeFormatException occurs
Please enter a number
2
The converted integer is 2

Things are good when input is a number, now let's enter nothing, this time, Scanner will read empty String

Please enter a number

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)
at Main.main(Main.java:24)

Now, let's enter null

Please enter a number
null
Exception in thread "main" java.lang.NumberFormatException: For input string: "null"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at Main.main(Main.java:24)

So you can say that if input is not numeric than any method which converts String to number e.g. Integer.parseInt(), Float.parseFloat() and Double.parseDouble will throw java.lang.NumberFormatException.

Please enter a number
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.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at Main.main(Main.java:24)

This time, we got the NumberFormatException because we are trying to convert "1.0" which is a floating point String to an integer value, which is not right. If you had tried to convert "1.0" to float or double, it should have gone fine.

It's one of the easiest error to solve, here are the steps.

1) Check the error message, this exception says for which input String it has thrown this error e.g.

Exception in thread "main" java.lang.NumberFormatException: For input string: "null" means input was null.

Exception in thread "main" java.lang.NumberFormatException: For input string: "" means input was empty String

Exception in thread "main" java.lang.NumberFormatException: For input string: "F1" means input was F1 which is alphanumeric

Exception in thread "main" java.lang.NumberFormatException: For input string: "1.0" means input String was "1.0" and you were trying to convert it to Integral data type e.g. int, short, char, and byte.


The NumberFormatException can come in any type of Java application e.g. JSP, Servlet, Android Apps, Core Java application. It's one of the core exceptions and one of the most common errors in Java applications after NullPointerException and NoClassDefFoundError. It's also an unchecked exception, hence the following properties of unchecked exceptions are also applicable to it.

java.lang.numberformatexception for input string null - Cause and Solution


The only way to solve this error is correct the data. Find out from where you are getting your input String and correct the data their. On the other hand, you must catch this exception whenever you are trying to convert a String to number e.g. int, short, char, byte, long, float or double as shown below:

Here is the right code to convert String to integer in Java with proper exception handling:

  int number = 0; // or any appllication default value
    try {
      number = Integer.parseInt(input);
    } catch (NumberFormatException nfe) {
      nfe.printStackTrace();
    }

The Handing exception is one of the most important coding practices for writing secure and reliable Java programs and this is also used to differentiate an average programmer from a star developer. I strongly suggest experienced Java programmers join advanced core Java courses to learn things like Security and how to write Reliable and Secure Programs in Java


That's all about what is NumberFormatException and how to deal with it. Always remember that it's a RuntimeException so Java will not ask you to handle it but you must otherwise your application will crash if the user enters "afafsdfds" as their age which you expect an integer. This is why validation is also very important if you are taking user input.

Sometimes leading or trailing whitespace also cause this problem. So, make sure you trim the user input before parsing it. Alternatively, you can use Scanner's nextInt() and hasNextInt() method to take integer input from user. Now, it's the scanner's responsibility to parse those values and it does a good job especially with white space.


Other Java Error troubleshooting guides you may like
  • org.hibernate.MappingException: Unknown entity Exception in Java [solution]
  • How to deal with ArrayIndexOutOfBoundsException in Java? (approach)
  • How to connect to MySQL database from Java Program [steps]
  • Exception in thread "main" java.lang.ExceptionInInitializerError in Java Program [fix]
  • How to solve java.lang.UnsatisfiedLinkError: no ocijdbc11 in Java [solution]
  • java.io.IOException: Map failed and java.lang.OutOfMemoryError: Map failed  [fix]
  • How to fix java.lang.ClassNotFoundException: org.postgresql.Driver error in Java? [solution]
  • java.lang.ClassNotFoundException:org.Springframework.Web.Context.ContextLoaderListener [solution]
  • How to fix java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory (solution)
  • How to fix "variable might not have been initialized" error in Java? (solution)
  • java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver [solution
  • How to solve java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Java MySQL? [solution]
  • java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory? [solution]
  • 2 ways to solve Unsupported major.minor version 51.0 error in Java [solutions]
  • java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer (solution)
  • java.net.BindException: Cannot assign requested address: JVM_Bind [fix]
  • java.net.SocketException: Too many files open java.io.IOException [solution]
  • How to solve java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver in Java? [solution]
  • How to solve java.lang.classnotfoundexception sun.jdbc.odbc.jdbcodbcdriver [solution]
  • java.net.SocketException: Failed to read from SocketChannel: Connection reset by peer [fix]
  • General Guide to solve java.lang.ClassNotFoundException in Java [guide]
  • Could not create the Java virtual machine Invalid maximum heap size: -Xmx (solution)
  • Error: could not open 'C:\Java\jre8\lib\amd64\jvm.cfg' (solution)
  • Fixing Unsupported major.minor version 52.0 Error in Java [solution]

If you have any doubt about NumberFormatException and you are facing an error that you cannot solve, let me know and we can work together.

2 comments :

tushki said...

Being not a developer but a Tech Analyst, if I need to correct the data in DB then null values should be updated with what integer value as default since this column refers to other table and any value cant be used ?

Unknown said...

EXCEPTION- For input string: "+"

Post a Comment