The following code throws a NumberFormatException when a character value is passed in Integer class constructor instead of an integer value
class Wrap
{
public static void main(String...args)
{
Integer j=new Integer("s");
System.out.println(j);
}
}
And the following code throws an InputMismatchException when a character value is input by user instead of an integer value
import java.util.Scanner;
class User
{
public static void main(String...args)
{
Scanner obj=new Scanner(System.in);
int i=obj.nextInt();
int j=obj.nextInt();
System.out.println("sum of numbers input by user");
System.out.println(i+j);
}
}
Both the exceptions appear to be thrown in same scenarios, so how do they differ?
Lets look at the specification of these two exception classes :
InputMismatchException
is specific for theScanner
. It indicates invalid type, not necessarily an invalid number.NumberFormatException
is specific for trying to convert a non numeric string to a number.