NumberFormatException in Java with Examples
Last Updated :
18 Feb, 2022
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.
Return Type:
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).
Constructors:
- 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
Integer.parseInt("null") ;
2. The input string is empty
Float.parseFloat(“”) ;
3. The input string with leading and/or trailing white spaces
Integer abc=new Integer(“ 432 “);
4. The input string with extra symbols
Float.parseFloat(4,236);
5. The input string with non-numeric data
Double.parseDouble(“ThirtyFour”);
6. The input string is alphanumeric
Integer.valueOf(“31.two”);
7. The input string might exceed the range of the datatype storing the parsed string
Integer.parseInt(“1326589741236”);
8. Data type mismatch between input string value and the type of the method which is being used for parsing
Integer.parseInt("13.26");
Example:
Java
// Java Program to illustrate NumberFormatException
// Importing Scanner class to take
// input number from the user
import java.util.Scanner;
// Class
public class GFG {
// Main driver method
public static void main(String[] arg)
{
// Declaring an variable which
// holds the input number entered
int number;
// Creating a Scanner class object to
// take input from keyboard
// System.in -> Keyboard
Scanner sc = new Scanner(System.in);
// Condition check
// If condition holds true, Continue loop until
// valid integer is entered by user
while (true) {
// Display message
System.out.println("Enter any valid Integer: ");
// Try block to check if any exception occurs
try {
// Parsing user input to integer
// using the parseInt() method
number = Integer.parseInt(sc.next());
// Number can be valid or invalid
// If number is valid, print and display
// the message and number
System.out.println("You entered: "
+ number);
// Get off from this loop
break;
}
// Catch block to handle NumberFormatException
catch (NumberFormatException e) {
// Print the message if exception occurred
System.out.println(
"NumberFormatException occurred");
}
}
}
}
Output: The below output is for different numbers been entered by the user
Enter any valid Integer:
12,017
NumberFormatException occurred
Enter any valid Integer:
Sixty4
NumberFormatException occurred
Enter any valid Integer:
null
NumberFormatException occurred
Enter any valid Integer:
436.25
NumberFormatException occurred
Enter any valid Integer:
3.o
NumberFormatException occurred
Enter any valid Integer:
98562341789
NumberFormatException occurred
Enter any valid Integer:
1000
You entered: 1000
Similar Reads
NumberFormat setCurrency() method in Java with Examples
The setCurrency() method is a built-in method of the java.text.NumberFormat which sets the currency used by this number format when formatting currency values. This does not update the minimum or maximum number of fraction digits used by the number format. It overwrites the initially currency. Synta
2 min read
NotSerializableException in Java with Examples
Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly used in Hibernate, RMI, JPA, EJB, and JMS technologies. The reverse operation of serialization is called deserialization where byte-stream is converted into an object. The serialization and deseri
4 min read
NumberFormat parse() method in Java with Examples
The parse(str) method is a built-in method of the java.text.NumberFormat which parses text from the beginning of the given string to produce a number. The method may not use the entire text of the given string Syntax: public Number parse?(String str) Parameters: The function accepts a string str who
2 min read
NumberFormat parseObject() method in Java with Examples
The parseObject() method is a built-in method of the java.text.NumberFormat which parses a text from a string to produce a Number. The function attempts to parse text starting at a given index. When parsing occurs, the given index is set to the last character used, in case parsing fails, the given i
2 min read
NumberFormat setRoundingMode() method in Java with Examples
The setRoundingMode() method is a built-in method of the java.text.NumberFormat which sets the RoundingMode used in this NumberFormat. The subclasses which handle different rounding modes should override this method. Syntax: public void setRoundingMode(RoundingMode mode) Parameters: The function acc
2 min read
NumberFormat setMaximumFractionDigits() method in Java with Examples
The setMaximumFractionDigits() method is a built-in method of the java.text.NumberFormat which sets the maximum number of digits allowed in the fraction portion of a number.If the new value for maximumFractionDigits is less than the current value of minimumFractionDigits, then minimumFractionDigits
2 min read
NumberFormat setParseIntegerOnly() method in Java with Examples
The setParseIntegerOnly() method is a built-in method of the java.text.NumberFormat which sets whether or not numbers should be parsed as integers only. Syntax: public void setParseIntegerOnly(boolean val) Parameters: The function accepts a mandatory parameter val which specifies the value to be set
1 min read
NumberFormat setMinimumFractionDigits() method in Java with Examples
The setMinimumFractionDigits() method is a built-in method of the java.text.NumberFormat which sets the minimum number of digits allowed in the fraction portion of a number.If the new value for minimumFractionDigits is less than the current value of maximumFractionDigits, then maximumFractionDigits
2 min read
NumberFormat hashCode() method in Java with Examples
The hashCode() method is a built-in method of the java.text.NumberFormat returns a hash-code value for this given object of instance. Syntax: public int hashCode() Parameters: The function does not accepts any parameter. Return Value: The function returns the hash-code value. Below is the implementa
1 min read
Number.shortValue() method in java with examples
The shortValue() is an inbuilt method in Java from the java.lang.Number class. This method is used to convert the current number object into a short primitive type. This may involve rounding or truncation because the short data type in Java is a 16-bit signed integer with a value range from -32,768
2 min read