Java ошибка integer parseint

Error Message:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Ace of Clubs"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at set07102.Cards.main(Cards.java:68)
C:\Users\qasim\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1

means:

There was an error. We try to give you as much information as possible
It was an Exception in main thread. It's called NumberFormatException and has occurred for input "Ace of Clubs".
at line 65th of NumberFormatException.java which is a constructor,
which was invoked from Integer.parseInt() which is in file Integer.java in line 580,
which was invoked from Integer.parseInt() which is in file Integer.java in line 615,
which was invoked from method main in file Cards.java in line 68.

It has resulted in exit code 1

In other words, you tried to parse "Ace of Clubs" to an int what Java can’t do with method Integer.parseInt. Java has provided beautiful stacktrace which tells you exactly what the problem is. The tool you’re looking for is debugger and using breakpoints will allow you to inspect the state of you application at the chosen moment.

The solution might be the following logic in case you want to use parsing:

if (cards[index].startsWith("Ace")) 
    value = 1;
else if (cards[index].startsWith("King"))
    value = 12;
else if (cards[index].startsWith("Queen"))
    value = 11;
...
else {
    try {
        Integer.parseInt(string.substring(0, cards[index].indexOf(" "))); 
    } catch (NumberFormatException e){
        //something went wrong
    }
}

What is an Exception in Java?

An exception is an event, which occurs during the execution of a
program, that disrupts the normal flow of the program’s instructions.

-Documentation

Constructors and usage in Integer#parseInt

static NumberFormatException forInputString(String s) {
    return new NumberFormatException("For input string: \"" + s + "\"");
}

public NumberFormatException (String s) {
    super (s);
}

They are important for understanding how to read the stacktrace. Look how the NumberFormatException is thrown from Integer#parseInt:

if (s == null) {
    throw new NumberFormatException("null");
}

or later if the format of the input String s is not parsable:

throw NumberFormatException.forInputString(s); 

What is a NumberFormatException?

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

-Documentation

NumberFormatException extends IllegalArgumentException. It tells us that it’s more specialized IllegalArgumentException. Indeed, it’s used for highlighting that although, the argument type was correct (String) the content of the String wasn’t numeric (a,b,c,d,e,f are considered digits in HEX and are legal when needed).

How do I fix it?
Well, don’t fix the fact that it’s thrown. It’s good that it’s thrown. There are some things you need to consider:

  1. Can I read the stacktrace?
  2. Is the String which causes an Exception a null?
  3. Does it look like a number?
  4. Is it ‘my string’ or user’s input?
  5. to be continued

Ad. 1.

The first line of a message is an information that the Exception occurred and the input String which caused the problem. The String always follows : and is quoted ("some text"). Then you become interested in reading the stacktrace from the end, as the first few lines are usually NumberFormatException‘s constructor, parsing method etc. Then at the end, there is your method in which you made a bug. It will be pointed out in which file it was called and in which method. Even a line will be attached. You’ll see. The example of how to read the stacktrace is above.

Ad. 2.

When you see, that instead of "For input string:" and the input, there is a null (not "null") it means, that you tried to pass the null reference to a number. If you actually want to treat is as 0 or any other number, you might be interested in my another post on StackOverflow. It’s available here.

The description of solving unexpected nulls is well described on StackOverflow thread What is a NullPointerException and how can I fix it?.

Ad. 3.

If the String that follows the : and is quoted looks like a number in your opinion, there might be a character which your system don’t decode or an unseen white space. Obviously " 6" can’t be parsed as well as "123 " can’t. It’s because of the spaces. But it can occure, that the String will look like "6" but actually it’s length will be larger than the number of digits you can see.

In this case I suggest using the debugger or at least System.out.println and print the length of the String you’re trying to parse. If it shows more than the number of digits, try passing stringToParse.trim() to the parsing method. If it won’t work, copy the whole string after the : and decode it using online decoder. It’ll give you codes of all characters.

There is also one case which I have found recently on StackOverflow, that you might see, that the input looks like a number e.g. "1.86" and it only contains those 4 characters but the error still exists. Remember, one can only parse integers with #Integer#parseInt#. For parsing decimal numbers, one should use Double#parseDouble.

Another situation is, when the number has many digits. It might be, that it’s too large or too small to fit int or long. You might want to try new BigDecimal(<str>).

Ad. 4.

Finally we come to the place in which we agree, that we can’t avoid situations when it’s user typing «abc» as a numeric string. Why? Because he can. In a lucky case, it’s because he’s a tester or simply a geek. In a bad case it’s the attacker.

What can I do now? Well, Java gives us try-catch you can do the following:

try {
    i = Integer.parseInt(myString);
} catch (NumberFormatException e) {
    e.printStackTrace();
    //somehow workout the issue with an improper input. It's up to your business logic.
}

Error Message:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Ace of Clubs"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at set07102.Cards.main(Cards.java:68)
C:\Users\qasim\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1

means:

There was an error. We try to give you as much information as possible
It was an Exception in main thread. It's called NumberFormatException and has occurred for input "Ace of Clubs".
at line 65th of NumberFormatException.java which is a constructor,
which was invoked from Integer.parseInt() which is in file Integer.java in line 580,
which was invoked from Integer.parseInt() which is in file Integer.java in line 615,
which was invoked from method main in file Cards.java in line 68.

It has resulted in exit code 1

In other words, you tried to parse "Ace of Clubs" to an int what Java can’t do with method Integer.parseInt. Java has provided beautiful stacktrace which tells you exactly what the problem is. The tool you’re looking for is debugger and using breakpoints will allow you to inspect the state of you application at the chosen moment.

The solution might be the following logic in case you want to use parsing:

if (cards[index].startsWith("Ace")) 
    value = 1;
else if (cards[index].startsWith("King"))
    value = 12;
else if (cards[index].startsWith("Queen"))
    value = 11;
...
else {
    try {
        Integer.parseInt(string.substring(0, cards[index].indexOf(" "))); 
    } catch (NumberFormatException e){
        //something went wrong
    }
}

What is an Exception in Java?

An exception is an event, which occurs during the execution of a
program, that disrupts the normal flow of the program’s instructions.

-Documentation

Constructors and usage in Integer#parseInt

static NumberFormatException forInputString(String s) {
    return new NumberFormatException("For input string: \"" + s + "\"");
}

public NumberFormatException (String s) {
    super (s);
}

They are important for understanding how to read the stacktrace. Look how the NumberFormatException is thrown from Integer#parseInt:

if (s == null) {
    throw new NumberFormatException("null");
}

or later if the format of the input String s is not parsable:

throw NumberFormatException.forInputString(s); 

What is a NumberFormatException?

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

-Documentation

NumberFormatException extends IllegalArgumentException. It tells us that it’s more specialized IllegalArgumentException. Indeed, it’s used for highlighting that although, the argument type was correct (String) the content of the String wasn’t numeric (a,b,c,d,e,f are considered digits in HEX and are legal when needed).

How do I fix it?
Well, don’t fix the fact that it’s thrown. It’s good that it’s thrown. There are some things you need to consider:

  1. Can I read the stacktrace?
  2. Is the String which causes an Exception a null?
  3. Does it look like a number?
  4. Is it ‘my string’ or user’s input?
  5. to be continued

Ad. 1.

The first line of a message is an information that the Exception occurred and the input String which caused the problem. The String always follows : and is quoted ("some text"). Then you become interested in reading the stacktrace from the end, as the first few lines are usually NumberFormatException‘s constructor, parsing method etc. Then at the end, there is your method in which you made a bug. It will be pointed out in which file it was called and in which method. Even a line will be attached. You’ll see. The example of how to read the stacktrace is above.

Ad. 2.

When you see, that instead of "For input string:" and the input, there is a null (not "null") it means, that you tried to pass the null reference to a number. If you actually want to treat is as 0 or any other number, you might be interested in my another post on StackOverflow. It’s available here.

The description of solving unexpected nulls is well described on StackOverflow thread What is a NullPointerException and how can I fix it?.

Ad. 3.

If the String that follows the : and is quoted looks like a number in your opinion, there might be a character which your system don’t decode or an unseen white space. Obviously " 6" can’t be parsed as well as "123 " can’t. It’s because of the spaces. But it can occure, that the String will look like "6" but actually it’s length will be larger than the number of digits you can see.

In this case I suggest using the debugger or at least System.out.println and print the length of the String you’re trying to parse. If it shows more than the number of digits, try passing stringToParse.trim() to the parsing method. If it won’t work, copy the whole string after the : and decode it using online decoder. It’ll give you codes of all characters.

There is also one case which I have found recently on StackOverflow, that you might see, that the input looks like a number e.g. "1.86" and it only contains those 4 characters but the error still exists. Remember, one can only parse integers with #Integer#parseInt#. For parsing decimal numbers, one should use Double#parseDouble.

Another situation is, when the number has many digits. It might be, that it’s too large or too small to fit int or long. You might want to try new BigDecimal(<str>).

Ad. 4.

Finally we come to the place in which we agree, that we can’t avoid situations when it’s user typing «abc» as a numeric string. Why? Because he can. In a lucky case, it’s because he’s a tester or simply a geek. In a bad case it’s the attacker.

What can I do now? Well, Java gives us try-catch you can do the following:

try {
    i = Integer.parseInt(myString);
} catch (NumberFormatException e) {
    e.printStackTrace();
    //somehow workout the issue with an improper input. It's up to your business logic.
}

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 60.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.

The NumberFormatException is an unchecked exception in Java that occurs when an attempt is made to convert a string with an incorrect format to a numeric value. Therefore, this exception is thrown when it is not possible to convert a string to a numeric type (e.g. int, float). For example, this exception occurs if a string is attempted to be parsed to an integer but the string contains a boolean value.

Since the NumberFormatException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor. It can be handled in code using a try-catch block.

What Causes NumberFormatException

There can be various cases related to improper string format for conversion to numeric values. Some of them are:

Null input string

Integer.parseInt(null);

Empty input string

Integer.parseInt("");

Input string with leading/trailing whitespaces

Integer myInt = new Integer(" 123  ");

Input string with inappropriate symbols

Float.parseFloat("1,234");

Input string with non-numeric data

Integer.parseInt("Twenty Two");

Alphanumeric input string

Integer.parseInt("Twenty 2");

Input string exceeding the range of the target data type

Integer.parseInt("12345678901");

Mismatch of data type between input string and the target data type

Integer.parseInt("12.34");

NumberFormatException Example

Here is an example of a NumberFormatException thrown when attempting to convert an alphanumeric string to an integer:

public class NumberFormatExceptionExample {
    public static void main(String args[]) {
        int a = Integer.parseInt("1a");
        System.out.println(a);
    }
}

In this example, a string containing both numbers and characters is attempted to be parsed to an integer, leading to a NumberFormatException:

Exception in thread "main" java.lang.NumberFormatException: For input string: "1a"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
    at java.base/java.lang.Integer.parseInt(Integer.java:652)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:3)

Such operations should be avoided where possible by paying attention to detail and making sure strings attempted to be parsed to numeric values are appropriate and legal.

How to Handle NumberFormatException

The NumberFormatException is an exception in Java, and therefore can be handled using try-catch blocks using the following steps:

  • Surround the statements that can throw an NumberFormatException in try-catch blocks
  • Catch the NumberFormatException
  • Depending on the requirements of the application, take necessary action. For example, log the exception with an appropriate message.

The code in the earlier example can be updated with the above steps:

public class NumberFormatExceptionExample {
    public static void main(String args[]) {
        try {
            int a = Integer.parseInt("1a");
            System.out.println(a);
        } catch (NumberFormatException nfe) {
            System.out.println("NumberFormat Exception: invalid input string");
        }
        System.out.println("Continuing execution...");
    }
}

Surrounding the code in try-catch blocks like the above allows the program to continue execution after the exception is encountered:

NumberFormat Exception: invalid input string
Continuing execution...

Track, Analyze and Manage Errors with Rollbar

Rollbar in action

Finding exceptions in your Java code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring, tracking and triaging, making fixing Java errors and exceptions easier than ever. Sign Up Today!

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.

Понравилась статья? Поделить с друзьями:
  • Java логирование ошибок
  • Java игнорирование ошибок
  • Java длинная ошибка
  • Java виды ошибок
  • Java деление на ноль какая ошибка