Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

NumberFormatException in Java — How to Fix (2026) | Tutorials Logic

What is This Error?

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.

Common Causes

  • String contains letters or special characters
  • Parsing a decimal string as integer (e.g., "12.5" with parseInt)
  • String has leading/trailing whitespace
  • Empty string or null passed to parse method
  • Number exceeds the type's range (overflow)

Quick Fix (TL;DR)

Quick Solution
// ❌ 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);
}

Common Scenarios & Solutions

Scenario 1: User Input Validation

Problem
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"!
Solution
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);

Scenario 2: Parsing Decimal as Integer

Problem
String price = "19.99";
int p = Integer.parseInt(price); // NumberFormatException! "19.99" is not an int
Solution
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

Scenario 3: Whitespace in String

Problem
String input = " 42 "; // Has spaces!
int num = Integer.parseInt(input); // NumberFormatException!
Solution
String input = " 42 ";
int num = Integer.parseInt(input.trim()); // ✅ Always trim first!

Scenario 4: Safe Parsing Helper Method

Solution
// ✅ Reusable safe parse method
public static Optional 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")
);

Best Practices to Avoid This Error

  • Always trim() before parsing - Remove leading/trailing whitespace
  • Validate with regex before parsing - Use matches("-?\\d+") for integers
  • Use try-catch for user input - Users can type anything
  • Use the right parse method - parseInt for int, parseDouble for decimals
  • Create safe parse helper methods - Reusable validation logic
  • Use BigDecimal for money - Avoids floating-point precision issues
  • Check for null/empty before parsing - Prevent NullPointerException too

Related Errors

Key Takeaways
  • NumberFormatException is thrown when a String cannot be converted to a number
  • Always call trim() before parsing to remove whitespace
  • Use parseInt for integers, parseDouble for decimals — don't mix them
  • Wrap parsing in try-catch when handling user input
  • Use regex validation before parsing for cleaner code
  • Use BigDecimal for monetary values to avoid floating-point precision issues

Frequently Asked Questions


Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.