
What is NumberFormatException?
java.lang.NumberFormatException is an unchecked exception thrown in Java when an application tries to convert a string into a numeric type (like int, float, double, etc.), but the string is not in a convertible format. This typically happens when using methods like Integer.parseInt(), Double.parseDouble(), or Float.parseFloat().
For example, if you try to parse the string "123" into an integer, it will work perfectly. However, if you try to parse "abc" or "12.3" into an integer, a NumberFormatException will be thrown.
Common Causes and Solutions
Letโs look at the common scenarios that lead to this exception and how to prevent or handle them.
1. String Contains Non-Numeric Characters
The most frequent cause is trying to parse a string that contains letters, symbols, or other characters that are not digits.
Problematic Code:
public class Main {
public static void main(String[] args) {
String notANumber = "hello123";
int number = Integer.parseInt(notANumber); // Throws NumberFormatException
System.out.println(number);
}
}
Solution:
You should validate the string before parsing it. A try-catch block is the standard way to handle this exception gracefully.
Corrected Code:
public class Main {
public static void main(String[] args) {
String notANumber = "hello123";
try {
int number = Integer.parseInt(notANumber);
System.out.println(number);
} catch (NumberFormatException e) {
System.err.println("The string is not a valid integer: " + notANumber);
// e.printStackTrace(); // For debugging
}
}
}
This code will catch the exception and print a user-friendly error message instead of crashing the program.
2. String Contains Whitespace
Leading or trailing whitespace in the string can also cause a NumberFormatException.
Problematic Code:
String withWhitespace = " 123 ";
int number = Integer.parseInt(withWhitespace); // Throws NumberFormatException
Note: Integer.parseInt() can actually handle whitespace since Java 1.4, but other parsers or older versions might not. Itโs still good practice to trim the string.
Solution:
Use the trim() method of the String class to remove any leading or trailing whitespace before parsing.
Corrected Code:
String withWhitespace = " 123 ";
try {
int number = Integer.parseInt(withWhitespace.trim());
System.out.println(number); // Output: 123
} catch (NumberFormatException e) {
System.err.println("Error parsing string with whitespace.");
}
3. Parsing a Floating-Point Number as an Integer
If you try to parse a string representing a floating-point number (e.g., "19.99") using Integer.parseInt(), it will fail because the period (.) is not a valid character for an integer.
Problematic Code:
String floatString = "19.99";
int number = Integer.parseInt(floatString); // Throws NumberFormatException
Solution:
First, parse the string into a Double or Float, and then, if necessary, cast it to an int.
Corrected Code:
String floatString = "19.99";
try {
double doubleValue = Double.parseDouble(floatString);
int number = (int) doubleValue; // Casting to int
System.out.println(number); // Output: 19
} catch (NumberFormatException e) {
System.err.println("The string is not a valid number: " + floatString);
}
4. Special Characters or Symbols
Strings containing currency symbols, commas, or other special characters cannot be parsed directly.
Problematic Code:
String currencyValue = "$1,000";
int number = Integer.parseInt(currencyValue); // Throws NumberFormatException
Solution: You need to preprocess the string to remove these special characters before parsing.
Corrected Code:
String currencyValue = "$1,000";
try {
String cleanString = currencyValue.replace("$", "").replace(",", "");
int number = Integer.parseInt(cleanString);
System.out.println(number); // Output: 1000
} catch (NumberFormatException e) {
System.err.println("Error parsing currency string.");
}
Best Practices for Prevention
- Always use a
try-catchblock: Never assume a string will be in the correct format. Wrapping parsing logic in atry-catchblock is the safest way to prevent your application from crashing. - Validate input: Before attempting to parse, validate the user input. You can use regular expressions to check if a string contains only numeric characters.
- Preprocess strings: Use methods like
trim()andreplace()to clean up strings before parsing them.
By following these guidelines, you can effectively handle NumberFormatException and make your Java applications more robust and user-friendly.
Professional Depth Check
For How to Handle java.lang.NumberFormatException, the practical standard is not whether the reader can repeat one instruction once. Treat the topic as a reproducible debugging procedure: verify JDK version, build tool configuration, classpath or module path, and runtime stack trace before drawing a conclusion. The result should be written as a small decision record, because future readers need to know which fact was observed, which assumption was used, and which condition would change the answer.
Evidence That Makes the Guidance Reliable
Use objective evidence before changing a workflow. Good evidence includes java -version, javac -version, Maven or Gradle output, and the smallest failing class. If two pieces of evidence conflict, keep the conflict visible instead of smoothing it over. For example, a successful quick fix is still weak evidence if the same input, account, dependency, or device state has not been tested again. A durable article should help the reader distinguish a confirmed fix from a plausible fix.
Review Table
| Review Item | What To Confirm | Why It Matters |
|---|---|---|
| Scope | The exact case covered by this article | Prevents over-applying the advice |
| Baseline | The state before any change | Makes rollback and comparison possible |
| Change | The smallest action taken | Reduces hidden side effects |
| Result | The observed output after the change | Separates evidence from expectation |
| Recheck | When to revisit the conclusion | Keeps the post accurate over time |
Edge Cases and Failure Modes
The main risks are fixing the symptom while leaving the root cause, and mixing unrelated changes into the same test. When the situation involves production data, personal information, money, health, legal rights, or security recovery, the conservative path is to stop and collect evidence before applying a broad fix. The same title can describe very different cases, so the reader should compare their environment with the assumptions in the post before copying commands or decisions.
Maintenance Standard
Recheck this guidance after dependency, operating-system, or build-tool changes. A useful update does not need to rewrite the entire post; it should confirm whether the examples, links, commands, screenshots, and decision criteria still match current behavior. If the old conclusion remains valid, record the check date. If it changes, explain what changed and why the previous advice is no longer enough.
Related Reading
Continue with these related posts from the same topic area.
Leave a comment