NumberFormatException in Java – Causes, Examples, and Complete Fix Guide

NumberFormatException is one of the most common runtime exceptions in Java. It occurs when a program attempts to convert a String into a numeric data type, such as int, double, long, or float, but the String does not contain a valid numeric value.

This exception is frequently encountered when processing user input, reading data from files, parsing JSON or CSV files, handling API responses, or working with databases. Understanding why this exception occurs and how to prevent it is an essential skill for every Java developer.

In this guide, you’ll learn what NumberFormatException is, why it occurs, common causes, real-world examples, and the best ways to fix and prevent it.

What is NumberFormatException?

NumberFormatException is a subclass of the IllegalArgumentException class and belongs to the java.lang package.

It is thrown when Java cannot convert a String into the requested numeric type because the String contains invalid characters or is not formatted correctly.

Example error:

Exception in thread “main”

java.lang.NumberFormatException: For input string: “ABC”

This means Java attempted to convert the String “ABC” into a number, but it is not a valid numeric value.

Why Does NumberFormatException Occur?

Java provides methods such as:

  • Integer.parseInt()
  • Long.parseLong()
  • Double.parseDouble()
  • Float.parseFloat()
  • Short.parseShort()
  • Byte.parseByte()

These methods expect a properly formatted numeric String.

If the String contains:

  • Letters
  • Special characters
  • Extra spaces
  • Empty values
  • Invalid decimal formats
  • Numbers outside the supported range

Java throws NumberFormatException.

Common Causes of NumberFormatException

Some common reasons include:

  • Converting alphabetic strings
  • Parsing empty strings
  • Parsing strings containing spaces
  • Invalid decimal numbers
  • Numbers exceeding the allowed range
  • Incorrect user input
  • Null values
  • Currency symbols
  • Comma-separated numbers
  • Improper data read from files or APIs

Example That Causes NumberFormatException

Incorrect example:


public class Main {

    public static void main(String[] args) {

        String value = "Java";

        int number = Integer.parseInt(value);

        System.out.println(number);
    }
}

Output:

Exception in thread “main”
java.lang.NumberFormatException:
For input string: “Java”

Since “Java” is not a valid integer, Java throws the exception.

Solution 1: Validate User Input

Always validate input before converting it.

Example:


String value = "123";

if (value.matches("-?\\d+")) {

    int number = Integer.parseInt(value);

    System.out.println(number);
}

The regular expression ensures the String contains only digits (and an optional leading minus sign) before conversion.

Solution 2: Use try-catch

The most common solution is to handle the exception.

Example:


public class Main {

    public static void main(String[] args) {

        String value = "ABC";

        try {

            int number = Integer.parseInt(value);

            System.out.println(number);

        } catch (NumberFormatException e) {

            System.out.println("Invalid number.");
        }
    }
}

Output:

Invalid number.

Using try-catch prevents the program from terminating unexpectedly.

Solution 3: Remove Leading and Trailing Spaces

Strings with extra spaces often cause problems.

Incorrect:


String value = " 123 ";
Integer.parseInt(value);

Correct:


String value = " 123 ".trim();
int number = Integer.parseInt(value);

The trim() method removes unnecessary whitespace.

Solution 4: Check for Empty Strings

An empty String cannot be converted into a number.

Incorrect:


String value = "";
Integer.parseInt(value);

Correct:


if (!value.isEmpty()) {

    int number = Integer.parseInt(value);
}

Always verify that the String is not empty before parsing.

Solution 5: Handle Null Values

Parsing a null reference results in an exception.

Incorrect:


String value = null;
Integer.parseInt(value);

Correct:


if (value != null) {
    int number = Integer.parseInt(value);
}

Always check for null when working with external input.

Solution 6: Remove Formatting Characters

Numbers may contain commas or currency symbols.

Incorrect:


String salary = "$10,000";
Integer.parseInt(salary);

Correct:


salary = salary.replace("$", "")
               .replace(",", "");
int value = Integer.parseInt(salary);

Output:

10000

Solution 7: Verify Numeric Range

Some values exceed the limits of the target data type.

Incorrect:


String value = "999999999999";
int number = Integer.parseInt(value);

Output:

NumberFormatException

Correct:


long number = Long.parseLong(value);
Choose an appropriate numeric type.

Solution 8: Parse Decimal Numbers Correctly

Attempting to convert a decimal value into an integer causes an exception.

Incorrect:


String value = "12.5";
Integer.parseInt(value);

Correct:


double number = Double.parseDouble(value);

Always use the correct parsing method for the expected data type.

Solution 9: Use Scanner Carefully

Incorrect:


Scanner scanner = new Scanner(System.in);
int number = Integer.parseInt(scanner.nextLine());

If the user enters:

abc

the program throws NumberFormatException.

Better approach:


try {

    int number =
        Integer.parseInt(scanner.nextLine());

} catch (NumberFormatException e) {

    System.out.println("Please enter a valid integer.");
}

Solution 10: Use Regular Expressions

Regular expressions help verify input before parsing.

Example:


String value = "250";
boolean valid =
        value.matches("\\d+");

If valid is true, parsing can proceed safely.

Solution 11: Validate API and File Data

Data from APIs, CSV files, or databases may contain unexpected values.

Example CSV:


101
102
ABC
104

Always validate each value before parsing.

Example:


try {

    int id = Integer.parseInt(value);

} catch (NumberFormatException e) {

    System.out.println("Invalid record.");
}

This prevents a single invalid value from crashing the entire application.

Solution 12: Create Utility Methods

Instead of repeating validation logic, create reusable methods.

Example:


public static Integer parseInteger(String value) {

    try {

        return Integer.parseInt(value);

    } catch (NumberFormatException e) {

        return null;
    }
}

This centralizes error handling and keeps your code cleaner.

Real-World Example

Incorrect implementation:


public class Main {

    public static void main(String[] args) {

        String age = "Twenty";

        int value = Integer.parseInt(age);

        System.out.println(value);
    }
}

Output:

Exception in thread “main”
java.lang.NumberFormatException:
For input string: “Twenty”

Correct implementation:


public class Main {

    public static void main(String[] args) {

        String age = "25";

        try {

            int value = Integer.parseInt(age);

            System.out.println(value);

        } catch (NumberFormatException e) {

            System.out.println("Invalid age.");
        }
    }
}

Output:

25

Common Scenarios That Cause NumberFormatException

Scenario Solution
Alphabetic input Validate input before parsing
Empty String Check with isEmpty()
Null value Verify the value is not null
Leading or trailing spaces Use trim()
Decimal value parsed as integer Use Double.parseDouble()
Number exceeds integer range Use Long.parseLong() or BigInteger
Currency symbols Remove formatting characters
Comma-separated numbers Remove commas before parsing
User input Use try-catch and validation
File or API data Validate every record before conversion

Best Practices to Prevent NumberFormatException

Follow these recommendations:

  • Always validate user input before parsing.
  • Use try-catch when converting Strings to numbers.
  • Remove unnecessary spaces with trim().
  • Check for null and empty values.
  • Use the correct parsing method (Integer, Long, Double, etc.).
  • Validate external data from files, APIs, and databases.
  • Avoid assuming input is always numeric.
  • Create reusable utility methods for parsing.
  • Display meaningful error messages to users.
  • Test your application with invalid and boundary inputs.

Frequently Asked Questions (FAQs)

What is NumberFormatException?

NumberFormatException is a runtime exception thrown when Java cannot convert a String into a numeric value because the String is not properly formatted.

Which methods throw NumberFormatException?

Common methods include:

  • Integer.parseInt()
  • Long.parseLong()
  • Double.parseDouble()
  • Float.parseFloat()
  • Short.parseShort()
  • Byte.parseByte()

How do I fix NumberFormatException?

You can fix it by:

  • Validating input before parsing.
  • Using try-catch.
  • Removing spaces with trim().
  • Checking for null and empty Strings.
  • Using the correct numeric parsing method.
  • Ensuring the value falls within the supported range.

Is NumberFormatException a checked exception?

No. NumberFormatException is an unchecked exception because it extends RuntimeException. It is not required to be declared or caught, but handling it is recommended when processing external or user-provided input.

Conclusion

NumberFormatException is one of the most frequently encountered runtime exceptions in Java, especially when converting Strings into numeric values. It is usually caused by invalid input, formatting issues, empty or null values, or numbers outside the supported range. By validating input, using try-catch blocks, selecting the appropriate parsing method, and sanitizing data before conversion, you can prevent this exception and build Java applications that are more robust, user-friendly, and reliable.

Related Java Tutorials