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

The NumberFormatException is i of the most mutual errors inward Java application along alongside NullPointerException. This mistake comes when y'all endeavour to convert a String into numeric information types e.g. int, float, double, long, short, char or byte. The information type conversion methods similar Integer.parseInt(), Float.parseFloat(), Double.parseDoulbe(), too Long.parseLong() throws NumberFormatException to signal that input String is non valid numeric value. Even though the beginning drive is ever something which cannot move converted into a number, at that topographic point are many reasons too input due to which NumberFormatException occurs inward Java application. Most of the fourth dimension I convey faced this mistake piece converting a String to int or Integer inward Java, but at that topographic point are other scenarios equally good when this mistake occurs. In this article, I am sharing 10 of the most mutual reasons of java.lang.NumberFormatException inward Java programs.

Having cognition of these drive volition assistance y'all to understand, analyze too solve this mistake inward your Java application. In each case, you'll come across an mistake message too so I'll explicate the argue behind it. It's hard to comprehend all scenarios on which JVM throws this mistake but I convey tried to capture equally many equally possible here. If y'all detect whatever other reasons or faced this mistake inward your Java projection due to anything mentioned below so delight part alongside us via comments.




10 mutual reasons of NumberFormatException 

Here are 10 reasons which I convey seen causing NumberFormatException inward Java application. If y'all convey whatever argue which is non listed hither but y'all convey seen them causing this error, experience complimentary to add together it.


1. Null Value
Since String is an object, it's possible that it could move null too if y'all overstep a null String to a method similar parseInt(), it volition throw NumberFormatException because zip is non 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 tin give the axe come across that mistake message equally good contains the declaration to parseInt() which is zip too that's the argue of this error. Thanks to JDK developers for printing the declaration equally good too a lesson to all Java developers who create their custom Exception class, ever impress the input which failed the process.  If y'all desire to acquire to a greater extent than almost best practices, read Java Coding Guidelines.

 is i of the most mutual errors inward Java application along alongside  10 Reasons of java.lang.NumberFormatException inward Java  - Solution



2. Empty String
Another mutual argue of java.lang.NumberFormatException is an empty String value. Many developers intend empty String is OK too parseInt() volition provide null or something, but that's non true. The parseInt(), or parseFloat() both volition throw NumberFormat mistake equally 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 y'all tin give the axe come across that this method has printed the input, which is empty String too which caused the failure.


3. Alphanumeric Input
Another mutual argue for NumberFormatException is the alphanumeric input. No non-numeric alphabetic lineament other than + too - is non permitted inward 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 tin give the axe come across that our input contains "A" which is non permitted, thence it caused the error, but y'all should retrieve that H5N1 is a valid alphabetic lineament when y'all convert String to an integer inward hexadecimal base. See Java: How to Program yesteryear Dietel too Dietel to acquire to a greater extent than almost information type conversion inward Java.



4. Leading space
You won't believe but leading too trailing spaces are i of the major reasons of NumberFormatException inward Java, y'all volition intend that input String " 123" is Ok but it's not. It has a leading infinite inward 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 mistake inward log files, especially trailing one. So, pay special attending to leading too trailing infinite piece converting String to long inward Java, if possible role trim() before passing String to parseLong() method.


5. Trailing space
Similar to inward a higher house issue, trailing infinite is to a greater extent than or less other nous argue for numerous NumberFormatException inward Java. H5N1 trailing white infinite is harder to spot than a leading white space, item inward 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 mistake y'all 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 y'all volition come across an mistake message similar Exception inward thread "main" java.lang.NumberFormatException: "null", this is dissimilar than the outset scenario. In the outset case, nosotros convey a null value, hither nosotros convey a "null" String i.e. an initialized String object whose value is "null". Since this is equally good non numeric, parseInt(), or parseFloat() volition throw the NumberFormat exception equally 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 y'all are non familiar alongside the concept of zip inward Java, delight come across Core Java Volume 1 - Fundamentals yesteryear Cay S. Horstmann to acquire more.



7. Floating indicate String
This is piddling chip different, fifty-fifty though "1.0" is perfectly valid String i.e. it doesn't incorporate whatever alphanumeric String but if y'all endeavour to convert it into integer values using parseInt(), parseShort(), or parseByte() it volition throw NumberFormatException because "1.0" is a floating indicate value too cannot move converted into integral one. These methods don't cast they but create 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, move careful piece converting floating indicate String to numbers, they tin give the axe solely move converted to float or double, but non on integral types similar byte, short, or int.



8. Out of make value
Another rare argue of java.lang.NumberFormatException is out-of-range value. For example, if y'all endeavour to convert String "129" to a byte value it volition throw NumberFormatException because maximum positive number byte tin give the axe stand upward for 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 y'all are non familiar alongside information types too their make inward Java, delight come across Core Java for the Impatient for to a greater extent than information.



9. Non-printable character
While working inward the software industry, sometimes y'all confront an termination where y'all intend the calculator is wrong, it has gone mad, the input String looks perfectly OK but however Java is throwing NumberFormatException, this happens but at the end, y'all volition realize that calculator is ever right.

For example, consider this mistake 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() too it volition run fine so why java.lang.NumberFormatException? It turns out that at that topographic point was a non-printable grapheme inward front end of 1 which was non displaying inward the house where y'all are seeing. So, scout out for the non-printable grapheme if y'all are facing weird error.



10. Similar characters e.g 1 too l
This is the unopen cousin of before error, this fourth dimension equally good our optic believes that input String is valid too intend that calculator has gone mad, but it wasn't. Only later spending hours y'all realize that Java was right, the String y'all are trying to convert into number was non numeric i "1" instead it was little instance alphabetic lineament L i.e. "l". You tin give the axe come across it's really subtle too non obvious from naked optic unless y'all are actually 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 mistake message, it looks similar the mistake is for numeric String "1". So move careful alongside this.

Here is the prissy slide to combine all these reasons into one, which y'all tin give the axe part equally good :

 is i of the most mutual errors inward Java application along alongside  10 Reasons of java.lang.NumberFormatException inward Java  - Solution


That's all almost 10 mutual reasons of java.lang.NumberFormatException too how to solve them. It's i of those errors where y'all quest to investigate to a greater extent than almost information than code. You quest to detect the source of invalid information too right it. In code, but brand certain y'all grab the NumberFormatException whenever y'all convert a String to number inward Java. Also, if y'all acquire input from the user, brand certain y'all perform validation. Use Scanner if taking input from ascendence business too methods similar nextInt() to straight read integer instead of reading String too so parsing it to int i time to a greater extent than using parseInt() method, solely to move greeted yesteryear NumberFormatExcpetion.


Other Java troubleshooting tutorials you may similar to explore
  • How to create "Error: Could non detect or charge nous class" inward Eclipse? (guide)
  • How to avoid ConcurrentModificationException inward Java? (tutorial)
  • How to solve "could non create the Java virtual machine" mistake inward Java? (solution)
  • How to create "illegal start of expression" compile fourth dimension mistake inward Java? (tutorial)
  • Fixing java.lang.unsupportedclassversionerror unsupported major.minor version 50.0 (solution)
  • Cause too solution of "class, interface, or enum expected" compiler mistake inward Java? (fix)
  • java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory mistake (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 inward Java? (solution)
  • java.lang.ClassNotFoundException : org.Springframework.Web.Context.ContextLoaderListener (solution)
  • How to solve "variable mightiness non convey initialized" compile fourth dimension mistake inward Java? (answer)
  • How to create 'javac' is non recognized equally an internal or external command (solution)
  • How to create Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger (solution)
  • How to solve java.lang.OutOfMemoryError: Java Heap Space inward Eclipse, Tomcat? (solution)


References
NumberFormatException inward Java SE 8


Subscribe to receive free email updates:

0 Response to "10 Reasons of java.lang.NumberFormatException inwards Java - Solution"

Posting Komentar