Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaNumberFormatException in Java with Examples

NumberFormatException in Java with Examples

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, trycatch 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:

  1. public NumberFormatException(): Constructs a NumberFormatException with no detail message.
  2. 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

RELATED ARTICLES

Most Popular

Recent Comments