0
0
JavaConceptBeginner · 3 min read

What is NumberFormatException in Java: Explanation and Example

NumberFormatException in Java is an error that happens when you try to convert a string into a number but the string does not have the right format. It is a type of RuntimeException that signals invalid number conversion.
⚙️

How It Works

Imagine you have a box labeled "numbers" and you want to put a string inside that box only if it looks like a number. If the string has letters or symbols that don't belong in a number, the box refuses to accept it and throws an error. In Java, this error is called NumberFormatException.

This exception happens when methods like Integer.parseInt() or Double.parseDouble() try to turn a string into a number but find characters that don't fit the number rules. For example, trying to convert "abc" or "123abc" into an integer will cause this error.

💻

Example

This example shows what happens when you try to convert a bad string into a number. The program catches the error and prints a message.

java
public class NumberFormatExample {
    public static void main(String[] args) {
        String badNumber = "123abc";
        try {
            int num = Integer.parseInt(badNumber);
            System.out.println("Number is: " + num);
        } catch (NumberFormatException e) {
            System.out.println("Error: Cannot convert '" + badNumber + "' to a number.");
        }
    }
}
Output
Error: Cannot convert '123abc' to a number.
🎯

When to Use

You encounter NumberFormatException when your program reads input as text but expects numbers. This often happens when reading user input, files, or data from the internet.

To handle this, you should always check or catch this exception to avoid your program crashing. For example, if you ask a user to enter their age, you must make sure they typed a valid number before using it.

Key Points

  • NumberFormatException occurs when converting invalid strings to numbers.
  • It is a RuntimeException, so it does not need to be declared but should be handled.
  • Common methods causing it are Integer.parseInt() and Double.parseDouble().
  • Always validate or catch this exception when parsing user or external input.

Key Takeaways

NumberFormatException happens when a string cannot be converted to a number.
It is important to handle this exception to keep your program running smoothly.
Use try-catch blocks around number parsing methods to catch invalid input.
Validate input before parsing to prevent NumberFormatException.
Common parsing methods that throw this exception include Integer.parseInt and Double.parseDouble.