The NumberFormatException occurs when an attempt is made to convert a string with improper format into a numeric value. That means, when it is not possible to convert a string in any numeric type (float, int, etc), this exception is thrown. It is a Runtime Exception (Unchecked Exception) in Java. It is a subclass of IllegalArgumentException class. To handle this exception, try–catch block can be used.
While operating upon strings, there are times when we need to convert a number represented as a string into an integer type. The method generally used to convert String to Integer in Java is parseInt().
Usage of parseInt() method: As we already know there are two variants of this method namely as follows to get a better understanding
public static int parseInt(String s) throws NumberFormatException This function parses the string argument as a signed decimal integer.
public static int parseInt(String s, int radix) throws NumberFormatException This function parses the string argument as a signed integer in the radix specified by the second argument.
In simple words, both methods convert the string into its integer equivalent. The only difference being is that of the parameter radix. The first method can be considered as an equivalent of the second method with radix = 10 (Decimal).
- public NumberFormatException(): Constructs a NumberFormatException with no detail message.
- public NumberFormatException(String msg): Constructs a NumberFormatException with the detail message ‘msg’
Common Reasons for NumberFormatException:
There are various issues related to improper string format for conversion in numeric value. A few of them are:
1. The input string is null
2. The input string is empty
3. The input string with leading and/or trailing white spaces
Integer abc=new Integer(“ 432 “);
4. The input string with extra symbols
5. The input string with non-numeric data
6. The input string is alphanumeric
7. The input string might exceed the range of the datatype storing the parsed string
8. Data type mismatch between input string value and the type of the method which is being used for parsing
Output: The below output is for different numbers been entered by the user
Enter any valid Integer: 12,017 NumberFormatException occured Enter any valid Integer: Sixty4 NumberFormatException occured Enter any valid Integer: null NumberFormatException occured Enter any valid Integer: 436.25 NumberFormatException occured Enter any valid Integer: 3.o NumberFormatException occured Enter any valid Integer: 98562341789 NumberFormatException occured Enter any valid Integer: 1000 You entered: 1000
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.