The NumberFormatException is thrown when you try to convert a String to a numeric type (int, long, double, etc.) but the string doesn't contain a valid number. It's a subclass of IllegalArgumentException.
// ❌ Problem
int num = Integer.parseInt("abc"); // NumberFormatException!
// ✅ Solution 1: try-catch
try {
int num = Integer.parseInt(input.trim());
} catch (NumberFormatException e) {
System.out.println("Invalid number: " + input);
}
// ✅ Solution 2: Validate first
if (input.matches("-?\\d+")) {
int num = Integer.parseInt(input);
}
Scanner scanner = new Scanner(System.in);
System.out.print("Enter age: ");
String input = scanner.nextLine();
int age = Integer.parseInt(input); // Crashes if user types "twenty"!
Scanner scanner = new Scanner(System.in);
int age = -1;
while (age < 0) {
System.out.print("Enter age: ");
String input = scanner.nextLine().trim();
try {
age = Integer.parseInt(input);
if (age < 0 || age > 150) {
System.out.println("Please enter a valid age (0-150)");
age = -1;
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a number.");
}
}
System.out.println("Age: " + age);
String price = "19.99";
int p = Integer.parseInt(price); // NumberFormatException! "19.99" is not an int
String price = "19.99";
// ✅ Parse as double
double p = Double.parseDouble(price); // 19.99
// ✅ Or parse as int after truncating
int pInt = (int) Double.parseDouble(price); // 19
// ✅ Use BigDecimal for money
BigDecimal bd = new BigDecimal(price); // Exact representation
String input = " 42 "; // Has spaces!
int num = Integer.parseInt(input); // NumberFormatException!
String input = " 42 ";
int num = Integer.parseInt(input.trim()); // ✅ Always trim first!
// ✅ Reusable safe parse method
public static Optional<Integer> safeParseInt(String s) {
if (s == null || s.trim().isEmpty()) return Optional.empty();
try {
return Optional.of(Integer.parseInt(s.trim()));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
// Usage
safeParseInt("42").ifPresent(n -> System.out.println("Parsed: " + n));
safeParseInt("abc").ifPresentOrElse(
n -> System.out.println(n),
() -> System.out.println("Invalid number")
);
It's thrown when Integer.parseInt(), Double.parseDouble(), or similar methods receive a string that doesn't represent a valid number "” like "abc", "12.5" (for parseInt), or strings with spaces.
First parse as double, then cast: (int) Double.parseDouble("12.5") gives 12. Or use Math.round() to round: (int) Math.round(Double.parseDouble("12.5")) gives 13.
Use regex: input.matches("-?\d+") for integers, input.matches("-?\d+(\.\d+)?") for decimals. Or use try-catch which is simpler for most cases.
Integer.parseInt() returns a primitive int. Integer.valueOf() returns an Integer object (autoboxed). Both throw NumberFormatException for invalid input.
Use a try-catch loop that keeps asking until valid input is provided. Always trim() the input first. Provide clear error messages telling the user what format is expected.
Explore 500+ free tutorials across 20+ languages and frameworks.