Java lang numberformatexception
Java Exception Handling – NumberFormatException
Making our way through our in-depth Java Exception Handling series, today we’re taking a look at the java.lang.NumberFormatException. As you may suspect, the NumberFormatException is thrown when code attempts to convert an invalid String into one of the other generic numeric wrapper classes, such as Integer , Byte , Long , and so forth.
Throughout this article we’ll explore the java.lang.NumberFormatException in greater detail, looking at where it resides in the Java Exception Hierarchy, as well as looking at some basic and functional sample code that illustrates how NumberFormatExceptions might be commonly thrown. Let’s get going!
The Technical Rundown
- All Java errors implement the java.lang.Throwable interface, or are extended from another inherited class therein.
- java.lang.Exception inherits from java.lang.Throwable .
- java.lang.RuntimeException inherits from java.lang.Exception .
- java.lang.IllegalArgumentException then inherits from java.lang.RuntimeException .
- Finally, java.lang.NumberFormatException inherits from java.lang.ReflectiveOperationException .
Full Code Sample
Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.
When Should You Use It?
The abstract Number class is the core superclass that is used to represent numeric values which can be converted into the primitive types of byte , double , float , int , long , and short . As such, Java throws a java.lang.NumberFormatException when a failed attempt is made to convert into one of those types. In addition, each of the numeric primitive types has its own wrapper class, namely Byte , Double , Float , Integer , Long , and Short . Like most wrappers, these classes can be used to represent a value object of the underlying primitive type, while also providing additional functionality and methods (such as the MAX_VALUE field).
For our sample code we’re testing conversion from String to each of the wrapper class types using their built in parseType() method (e.g. Integer.parseInt() for the Integer class). Just to keep things tidy we’ll traverse through them in alphabetical order, starting with Byte , which we test in the convertStringToByte(String string) method:
As you can see, nothing fancy going on here. We merely take our passed String parameter and attempt to parse it via Byte.parseByte(String string) . If we catch an Exception we output it.
To call this method we have two different String values we’re trying: 20 and 200 .
As you’re probably aware, the maximum positive value of a Byte is 127 , so the first call works, but the second throws a java.lang.NumberFormatException , indicating that the value of 200 is out of range:
Next we have our Double testing method and executing code:
Here we’re trying three different values to show how we can use those build-in fields, like Double.MAX_VALUE . However, an unrecognizable character of x at the end of our third String value results in another java.lang.NumberFormatException :
Here’s our test for conversion to a Float object:
Our first value call works fine, as does the second, except the output is Infinity . This is because the maximum positive value of a Float is a little less than 2^39 , so while there’s no parse error, a Float object cannot handle that value so it wraps to an infinite representation. Our third call, however, again uses an invalid character of x instead of the exponent e , so another NumberFormatException is thrown:
For our Integer test we again use an invalid character of x :
As expected, the second call throws another NumberFormatException :
Next we have the Long value, which is essentially just the much larger form of an Integer :
As you can see by the comment, the maximum positive value of a Long is 2e63 — 1 , which we’ve converted to its decimal format as a String . Both these first two conversions work fine, but increasing the value to one above the MAX_VALUE produces another NumberFormatException :
Finally, we have the Short conversion. While Long is a much larger Integer , Short is limited to a far smaller value:
Again we’re testing using the maximum positive value of a Short ( 32,767 ), which works fine, but the increase to one more than that throws yet another NumberFormatException :
As we can see, NumberFormatExceptions can occur in a variety of scenarios, but typically they’re due to either typos in the numeric String values that are being parsed, or because the resultant value would exceed the bounds of the target object type.
The Airbrake-Java library provides real-time error monitoring and automatic exception reporting for all your Java-based projects. Tight integration with Airbrake’s state of the art web dashboard ensures that Airbrake-Java gives you round-the-clock status updates on your application’s health and error rates. Airbrake-Java easily integrates with all the latest Java frameworks and platforms like Spring , Maven , log4j , Struts , Kotlin , Grails , Groovy , and many more. Plus, Airbrake-Java allows you to easily customize exception parameters and gives you full, configurable filter capabilities so you only gather the errors that matter most.
Check out all the amazing features Airbrake-Java has to offer and see for yourself why so many of the world’s best engineering teams are using Airbrake to revolutionize their exception handling practices!
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 Number e.g. 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 e.g. 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 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 in code if you are catching this error and printing this in the log file for data analysis, but if you are not handling this exception then your application can crash, which is not good on Java developer’s part. See Core Java Fundamentals by Cay S. Horstman to learn more about the error and exception handling in Java.
In this article, I’ll show you an example of 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 e.g. a null cannot be converted to a number so you will NumberFormatException. 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 given format e.g. you expect an integer but 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 wants to learn more about how to convert one data type to another using valueOf() , toString() and parseXX() method, please see Big Java: Early Objects 5th Edition by Cay S. Horstmann.
Here is our Java program to show different scenarios where you may encounter NumberFormatException in Java:
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: «»
Now, let’s enter null
Please enter a number
Exception in thread «main» java.lang.NumberFormatException: For input string: «null»
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
Exception in thread «main» java.lang.NumberFormatException: For input string: «1.0»
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 exception and one of the most common errors in Java application after NullPointerException and NoClassDefFoundError. It’s also an unchecked exception, hence following properties of unchecked exceptions are also applicable to it.
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:
The Handing exception is one of the most important coding practice for writing secure and reliable Java programs and this is also used to differentiate an average programmer with a star developer. I strongly suggest experienced Java programmers to read Java Coding Guidelines: 75 Recommendations for Reliable and Secure Programs to learn more about such practices.
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 a 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 scanner’s responsibility to parse those value and it does a good job especially with white space.
Exception in thread «main» java.lang.NumberFormatException: For input string:
kazumahits Newbie Poster
pls help me to solve my problem.
here’s my code
how to prevent this error
Exception in thread «main» java.lang.NumberFormatException: For input string: «a»
this code will come out when i enter any letter
thanks for the answer god bless
- 7 Contributors
- forum28 Replies 8,161 Views 1 Week Discussion Span
- commentLatest Post 9 Years Ago by jon.kiparsky
It looks like you’re entering a non-integer value when you run the program. Does it do this when you enter a 1?
why dont you just use any other integer value instead of string «a» ? and the statement if (a==a) is not a good way to go .but if you have to have «a» , then my suggestion is that you first convert the string read from console into a char and then use statements like if (char==’a’)System.out.println(«you are a seniour»);
First of all, you should probably check for non-numeric values before you parse the input at line 11.
Another problem is this, at line 23:
I assume you want to check if the input was «a». In that case, it should be a.equals(«a»). Right now, you’re simply checking if the variable a is the same as itself, which will always return true.
If you really want to use «a» as an input value, there are two easy ways to do this. One is to catch that «a» first, and then do the parseint. The better way might be to put the parseint into a try block, and put the check for «a» into the catch block. Put a default case, in case they enter something that isn’t an int and isn’t «a».
sorry i forgot to remove that line.
is deleted on my jcreator
the main prob is how to terminate the exception error or put output message if you enter a letter
i’m sorry i did’nt notice that line, but if you remove that error its process complete without error
Okay, so you don’t want «a» as a value? Better still. Put a try block around the parseint, and use the catch block to alert the user («Please enter a number from 1 to 4») and set a «redo» flag. A do . while loop is the appropriate control structure here, where the condition would be . while (redo);
yah. but how to do it. sorry again i’m new in java
There are plenty of tutorials out there — try searching for «java try catch» or «java exception handling» and sort through what you find.
Briefly, try-catch-finally is a way of identifying a potential source of an exception (the code in the try block) and proivding instructions for dealing with the exception if it arises (the catch block). The «finally» block is code executed regardless of whether an exception arises.
The format is like this:
Go do some research, and come back if you have a specific question that reading half a dozen tutorials and articles doesn’t clear up.
try this one
Check this code. Hope this will solve your problem..
HERE A SHORTER WAY FOR YOU.INSTEAD OF USING CASCADING IF ELSE STATEMENT WHICH IS VERY HARD TO READ YOU CAN USE SWITCH STATEMENT WHICH IS A SHORTER WAY.
but that doesn’t really solve the problem, does it? Your suggestion still crashes in exactly the same way that the original does.
your way of attempting the question is wrong first of all you are entering integer and then you use an if condition to compare int and string that a==a thats wrong.
this is the way study it first.
Um, why is a an array?
Because at the same time it compare char value if you enter ‘a’ and also compare int value if you enter 1,2,3,or 4.
Really? How do you figure that? You never see an int value in that code, and you never use anything beyond a.
This isn’t a bad way to get around the original problem, the crash when entering a non-numeric value — but it seems like you need to look at the array part again.
What you’re doing is getting the input as a String and converting the first character you see to a char, and using that as a switch character. That’s a tolerable way to do it (though if you’re only getting or setting data, and not branching your code, you should use a lookup rather than a branch) but your explanation of the array suggests that you haven’t thought it through very much.
if you have a way do it and show. arguing is easily then to work on
Well, as I said, your way is a plausible solution for the input problem, since you’re not trying to do a forced conversion to a possibly unsuitable value. The obvious improvement would be to replace
And, as I said, using a lookup is generally a better procedure than a branch if your decision is simply about which data to use. It allows you to declare literal data in one spot in the code rather than losing it throughout the code, it’s more compact, meaning you can have the whole logic of the expression on screen, but there is no sacrifice of readability: an array lookup is easy to understand, and if you know the contents of the array, you know exactly what it’ll do. Furthermore, it reduces the chance for error, since you have fewer lines on which to make errors. Repeated case statements give you the opportunity to make mistakes in writing and then again in rewriting — you have to write the same thing over and over, and get it right each time, and then when you read it, you have to distinguish one minor variation — the error — in a field of similar lines. An array lookup is one line, and you have to get it right exactly once.
So, all things considered, I think that the alternative I posted above — putting the alternative strings into an array and then looking them up when needed — is the one I would prefer to write or to maintain. The value of a in that, of course, would come from a parseInt, using a try block as discussed above to handle and report erroneous input.