-
Couldn't load subscription status.
- Fork 4
Java NumberFormatException Example
Ramesh Fadatare edited this page Jul 12, 2019
·
1 revision
This Java example demonstrates the usage of java.lang.NumberFormatException class with an example. This NumberFormatException occurs when a string is parsed to any numeric variable.
From javaDoc - The NumberFormatException exception thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
package com.javaguides.corejava;
public class NumberFormatExceptionExample {
public static void main(String[] args) {
String str1 = "100ABCD";
try {
int x = Integer.parseInt(str1); // Converting string with inappropriate format
int y = Integer.valueOf(str1);
} catch (NumberFormatException e) {
System.err.println("NumberFormatException caught!");
e.printStackTrace();
}
}
}Output:
NumberFormatException caught!
java.lang.NumberFormatException: For input string: "100ABCD"
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.javaguides.corejava.NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:9)