Saturday, November 23, 2019

10 Reasons Of Java.Lang.Numberformatexception Inward Coffee - Solution

The NumberFormatException is ane of the most mutual errors inwards Java application along amongst NullPointerException. This mistake comes when yous endeavor 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(), as well as Long.parseLong() throws NumberFormatException to signal that input String is non valid numeric value. Even though the origin sweat is ever something which cannot live on converted into a number, in that location are many reasons as well as input due to which NumberFormatException occurs inwards Java application. Most of the fourth dimension I convey faced this mistake acre converting a String to int or Integer inwards Java, but in that location are other scenarios every bit good when this mistake occurs. In this article, I am sharing 10 of the most mutual reasons of java.lang.NumberFormatException inwards Java programs.

Having noesis of these sweat volition assistance yous to understand, analyze as well as solve this mistake inwards your Java application. In each case, you'll run across an mistake message as well as so I'll explicate the argue behind it. It's hard to embrace all scenarios on which JVM throws this mistake but I convey tried to capture every bit many every bit possible here. If yous detect whatsoever other reasons or faced this mistake inwards your Java projection due to anything mentioned below so delight portion amongst us via comments.




10 mutual reasons of NumberFormatException 

Here are 10 reasons which I convey seen causing NumberFormatException inwards Java application. If yous convey whatsoever argue which is non listed hither but yous convey seen them causing this error, experience costless to add together it.


1. Null Value
Since String is an object, it's possible that it could live on null as well as if yous overstep a null String to a method similar parseInt(), it volition throw NumberFormatException because nothing 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 sack run across that mistake message too contains the declaration to parseInt() which is nothing as well as that's the argue of this error. Thanks to JDK developers for printing the declaration every bit good as well as a lesson to all Java developers who create their custom Exception class, ever impress the input which failed the process.  If yous desire to larn to a greater extent than almost best practices, read Java Coding Guidelines.

 is ane of the most mutual errors inwards Java application along amongst  10 Reasons of java.lang.NumberFormatException inwards Java  - Solution



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


3. Alphanumeric Input
Another mutual argue for NumberFormatException is the alphanumeric input. No non-numeric missive of the alphabet other than + as well as - is non permitted inwards 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 sack run across that our input contains "A" which is non permitted, thence it caused the error, but yous should recollect that Influenza A virus subtype H5N1 is a valid missive of the alphabet when yous convert String to an integer inwards hexadecimal base. See Java: How to Program yesteryear Dietel as well as Dietel to larn to a greater extent than almost information type conversion inwards Java.



4. Leading space
You won't believe but leading as well as trailing spaces are ane of the major reasons of NumberFormatException inwards Java, yous volition intend that input String " 123" is Ok but it's not. It has a leading infinite inwards 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 location the leading or trailing mistake inwards log files, peculiarly trailing one. So, pay special attending to leading as well as trailing infinite acre converting String to long inwards Java, if possible run trim() before passing String to parseLong() method.


5. Trailing space
Similar to higher upwardly issue, trailing infinite is simply about other top dog argue for numerous NumberFormatException inwards Java. Influenza A virus subtype H5N1 trailing white infinite is harder to location than a leading white space, item inwards 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 yous 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 yous volition run across an mistake message similar Exception inwards thread "main" java.lang.NumberFormatException: "null", this is dissimilar than the kickoff scenario. In the kickoff 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 too non numeric, parseInt(), or parseFloat() volition throw the NumberFormat exception every bit 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 yous are non familiar amongst the concept of nothing inwards Java, delight run across Core Java Volume 1 - Fundamentals yesteryear Cay S. Horstmann to larn more.



7. Floating quest String
This is fiddling chip different, fifty-fifty though "1.0" is perfectly valid String i.e. it doesn't comprise whatsoever alphanumeric String but if yous endeavor to convert it into integer values using parseInt(), parseShort(), or parseByte() it volition throw NumberFormatException because "1.0" is a floating quest value as well as cannot live on converted into integral one. These methods don't cast they simply 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, live on careful acre converting floating quest String to numbers, they tin sack exclusively live on converted to float or double, but non on integral types similar byte, short, or int.



8. Out of hit value
Another rare argue of java.lang.NumberFormatException is out-of-range value. For example, if yous endeavor to convert String "129" to a byte value it volition throw NumberFormatException because maximum positive number byte tin sack stand upwardly 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 yous are non familiar amongst information types as well as their hit inwards Java, delight run across Core Java for the Impatient for to a greater extent than information.



9. Non-printable character
While working inwards the software industry, sometimes yous confront an effect where yous intend the calculator is wrong, it has gone mad, the input String looks perfectly OK but withal Java is throwing NumberFormatException, this happens but at the end, yous 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() as well as it volition run fine so why java.lang.NumberFormatException? It turns out that in that location was a non-printable grapheme inwards front end of 1 which was non displaying inwards the house where yous are seeing. So, sentinel out for the non-printable grapheme if yous are facing weird error.



10. Similar characters e.g 1 as well as l
This is the unopen cousin of before error, this fourth dimension too our oculus believes that input String is valid as well as intend that calculator has gone mad, but it wasn't. Only later spending hours yous realize that Java was right, the String yous are trying to convert into number was non numeric ane "1" instead it was little instance missive of the alphabet L i.e. "l". You tin sack run across it's real subtle as well as non obvious from naked oculus unless yous 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 live on careful amongst this.

Here is the prissy slide to combine all these reasons into one, which yous tin sack portion every bit good :

 is ane of the most mutual errors inwards Java application along amongst  10 Reasons of java.lang.NumberFormatException inwards Java  - Solution


That's all almost 10 mutual reasons of java.lang.NumberFormatException as well as how to solve them. It's ane of those errors where yous involve to investigate to a greater extent than almost information than code. You involve to detect the source of invalid information as well as right it. In code, simply brand certain yous choose grip of the NumberFormatException whenever yous convert a String to number inwards Java. Also, if yous acquire input from the user, brand certain yous perform validation. Use Scanner if taking input from dominance work as well as methods similar nextInt() to direct read integer instead of reading String as well as so parsing it to int in ane trial to a greater extent than using parseInt() method, exclusively to live on greeted yesteryear NumberFormatExcpetion.


Other Java troubleshooting tutorials you may similar to explore
  • How to create "Error: Could non detect or charge top dog class" inwards Eclipse? (guide)
  • How to avoid ConcurrentModificationException inwards Java? (tutorial)
  • How to solve "could non create the Java virtual machine" mistake inwards Java? (solution)
  • How to create "illegal start of expression" compile fourth dimension mistake inwards Java? (tutorial)
  • Fixing java.lang.unsupportedclassversionerror unsupported major.minor version 50.0 (solution)
  • Cause as well as solution of "class, interface, or enum expected" compiler mistake inwards 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 inwards Java? (solution)
  • java.lang.ClassNotFoundException : org.Springframework.Web.Context.ContextLoaderListener (solution)
  • How to solve "variable mightiness non convey initialized" compile fourth dimension mistake inwards Java? (answer)
  • How to create 'javac' is non recognized every bit 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 inwards Eclipse, Tomcat? (solution)


Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!



No comments:

Post a Comment