Java lang number format exception

The NumberFormatException is the frequently occurred exception in Java applications like NullPointerException.

NumberFormatException is an unchecked exception that occurred we try to convert a String to a number type.

Many Java methods 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.

In this article, we will see how the NumberFormatException exception occurred and ways to avoid NumberFormatExcpetion in Java.

Null String

Some times we see the Exception in thread "main" java.lang.NumberFormatException: "null". In the first case, In this, 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.

package com.javacodestuffs.core.exception.handling; public class NumberFormatForNull{ public static void main(String []args){ float ft = Float.parseFloat("null"); System.out.println(ft); } } output: Exception in thread "main" java.lang.NumberFormatException: For input string: "null" at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043) at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122) at java.lang.Float.parseFloat(Float.java:451) at NumberFormatForNull.main(NumberFormatForNull.java:4)

Converting Float to String

In this case "1.0" is perfectly valid String i.e. it doesn't contain any alphanumeric String. 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.

package com.javacodestuffs.core.exception.handling; public class NumberFormatForFloat { public static void main(String []args){ long lg = Long.parseLong("1.0"); System.out.println(lg ); } } output: 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:589) at java.lang.Long.parseLong(Long.java:631) at NumberFormatForFloat.main(NumberFormatForFloat.java:6)

Convert String to Out of range values

Suppose we have string "130" to a byte, It throws NumberFormatException as the given type byte has rage is 128, which is exceeded by us.

package com.javacodestuffs.core.exception.handling; public class NumberFormatForByte { public static void main(String []args){ byte bt = Byte.parseByte("129"); System.out.println(bt); } } output: Exception in thread "main" java.lang.NumberFormatException: Value out of range. Value:"129" Radix:10 at java.lang.Byte.parseByte(Byte.java:151) at java.lang.Byte.parseByte(Byte.java:175) at NumberFormatForByte.main(NumberFormatForByte.java:6)

Leading and Trailing space in String

This is a common error when we read values from the properties files and there are leading and trailing spaces present in the string.

If we want to convert " 128" into an integer, it will throw exception java.lang.NumberFormatException.

package com.javacodestuffs.core.exception.handling; public class NumberFormatForLeadingSpace { public static void main(String []args){ int thumbnailLength = Integer.parseInt(" 128"); System.out.println(thumbnailLength); } } Exception in thread "main" java.lang.NumberFormatException: For input string: " 128" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:569) at java.lang.Integer.parseInt(Integer.java:615) at com.javacodestuffs.core.exception.handling.NumberFormatForLeadingSpace.main(NumberFormatForLeadingSpace.java:6)

For Trailing Spaces

package com.javacodestuffs.core.exception.handling; public class NumberFormatForTrailingSpace { public static void main(String []args){ int thumbnailHeight = Integer.parseInt("128 "); System.out.println(thumbnailHeight); } } Exception in thread "main" java.lang.NumberFormatException: For input string: "128 " 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 com.javacodestuffs.core.exception.handling.NumberFormatForTrailingSpace.main(NumberFormatForTrailingSpace.java:6)

Alphanumeric Input

This is a common mistake by the programmer for the alphanumeric input. No non-numeric letter other than + and - is not permitted in the input string. It will throw an exception.

package com.javacodestuffs.core.exception.handling; public class NumberFormatForAlphanumeric { public static void main(String []args){ short sh = Short.parseShort("B6"); System.out.println(sh); } } output: Exception in thread "main" java.lang.NumberFormatException: For input string: "B6" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Short.parseShort(Short.java:118) at java.lang.Short.parseShort(Short.java:144) at com.javacodestuffs.core.exception.handling.NumberFormatForAlphanumeric.main(NumberFormatForAlphanumeric.java:6)

Empty String

This is the most common mistakes that happened from the programmer to convert an empty string to numeric or float values.

The parseInt(),parseFloat() ...etc will throw NumberFormatException.

package com.javacodestuffs.core.exception.handling; public class NumberFormatForAlphanumericEmptyString { public static void main(String[] args) { int value = Integer.parseInt(""); System.out.println(value); } } output: 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:592) at java.lang.Integer.parseInt(Integer.java:615) at com.javacodestuffs.core.exception.handling.NumberFormatForAlphanumericEmptyString.main(NumberFormatForAlphanumericEmptyString.java:6)

null values

This will happens when we pass null to a method like parseInt or parseFloat.It mostly occurs when we expect return values from some other methods and forgot to put a null check before converting it to our required type.

package com.javacodestuffs.core.exception.handling; public class NumberFormatForNullvalues { public static void main(String []args){ int value = Integer.parseInt(null); System.out.println(value); } } output: Exception in thread "main" java.lang.NumberFormatException: null at java.lang.Integer.parseInt(Integer.java:542) at java.lang.Integer.parseInt(Integer.java:615) at com.javacodestuffs.core.exception.handling.NumberFormatForNullvalues.main(NumberFormatForNullvalues.java:6)

characters e.g 1 and l

This is another mistake by the programmer. Consider or typo "1" as "l".

package com.javacodestuffs.core.exception.handling; public class NumberFormatForTypo { public static void main(String []args){ int value = Integer.parseInt("l"); System.out.println(value); } } output: 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:580) at java.lang.Integer.parseInt(Integer.java:615) at com.javacodestuffs.core.exception.handling.NumberFormatForTypo.main(NumberFormatForTypo.java:6)

Best Practices to avoid java.lang.NumberFormatException

1). Don't try to convert alphabetic or special characters into numbers – the Java Number
API cannot do that.

2). We may want to validate an input string using regular expressions and throw the exception for
the invalid characters.

3). We can sanitize input against foreseeable known issues with methods like trim() and replaceAll().

4). In some cases, special characters in input may be valid. So, we do special processing for
that, using NumberFormat.

5). validate the input before converting it to antother data types.

6). Checks whether the String a valid Java number.

7). Determine if a string is Int or Float and to represent in longer format.

String cost = ""; if (cost !=null && !"".equals(cost) ){ try { Integer intCost = Integer.parseInt(cost); List<Book> books = bookService.findBooksCheaperThan(intCost); } catch (NumberFormatException e) { System.out.println("Cost is not a number."); System.out.println(e.getMessage()); } }

Post/Questions related to Java lang number format exception

How to resolve number format exception in java?
How to resolve class cast exception in java?
How to fix "Error: Could not find or load main class" in Eclipse?
Ways to avoid ConcurrentModificationException in Java?
How to solve "could not create the Java virtual machine" error in Java?
How to fix "illegal start of expression" compile-time error in Java?
Cause and solution of "class, interface, or enum expected" compiler error in Java?
How to solve java.lang.ClassNotFoundException: com.mysql.jdbc.Driver error?
How to solve java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver?
Common reasons of java.lang.ArrayIndexOutOfBoundsException in Java?
java.lang.ClassNotFoundException : org.Springframework.Web.Context.ContextLoaderListener
How to solve "variable might not have initialized" compile-time error in Java?
How to fix 'javac' is not recognized as an internal or external command
How to solve java.lang.OutOfMemoryError: Java Heap Space in Eclipse, Tomcat?
Best Practices to Handle Exceptions in Java

In this article, we have seen the  Java lang number format exception with examples. All source code in the tutorial can be found in the GitHub repository.