Fix NumberFormatException When Parsing Numbers in Java
Fix NumberFormatException from parseInt and parseDouble by handling whitespace, empty input, overflow and locale-specific separators before you parse.

The message tells you the input that failed, and the quotation marks are the clue. Read them closely, because the whole diagnosis is in what sits between them:
java.lang.NumberFormatException: For input string: "42 "
java.lang.NumberFormatException: For input string: ""
java.lang.NumberFormatException: For input string: "3000000000"
java.lang.NumberFormatException: Cannot parse null stringEach of those is a different cause with a different fix. The first has a trailing space that the eye cannot see. The second is empty. The third is a perfectly valid number that does not fit in an int, whose largest value is 2,147,483,647. The fourth is null, which has its own wording. This post takes each case in turn with a fix you can paste, and then shows how to design the parsing so the exception does not reach your users. For where this sits among the language features, see the modern Java guide.
Whitespace and signs
Integer.parseInt accepts an optional leading + or - followed by digits, and nothing else. Not a space, not a thousands separator, not a trailing letter:
Integer.parseInt("42"); // 42
Integer.parseInt("+42"); // 42
Integer.parseInt(" 42"); // NumberFormatException
Integer.parseInt("42 "); // NumberFormatExceptionTrim before parsing, and prefer strip() to trim(). The older method removes only characters up to U+0020, while strip() removes all Unicode whitespace:
int quantity = Integer.parseInt(input.strip());Values copied from a spreadsheet or a web page often contain a non-breaking space, U+00A0. It looks like a normal space in a log, trim() leaves it in place, and the exception message appears to quote a clean number. If strip() fixes the problem, that was the cause. When you cannot tell, print the code points of the string: input.chars().forEach(System.out::println) shows 160 where a plain space would show 32.
Empty and null input
static OptionalInt parseQuantity(String input) {
if (input == null || input.isBlank()) {
return OptionalInt.empty();
}
try {
return OptionalInt.of(Integer.parseInt(input.strip()));
} catch (NumberFormatException e) {
return OptionalInt.empty();
}
}The caller now decides what absence means, whether that is a default of one, a validation message or an error response, and the exception does not travel up the stack. Catching NumberFormatException here is reasonable because the input comes from outside the program. Do not use exceptions to steer control flow for data your own code produced; a bug there should fail loudly.
Overflow
"3000000000" is a legitimate number that needs 32 bits and a sign, and an int has only 31 bits of magnitude. Use a type that fits:
long big = Long.parseLong("3000000000");
BigInteger huge = new BigInteger("123456789012345678901234567890");Choose by the range you expect, not by the value that happened to fail today. An identifier from another system is safer as a long, or as a String if you never do arithmetic on it. For money, use BigDecimal, never double: new BigDecimal("19.99") parses the text exactly, whereas a double stores the nearest binary fraction. When you convert a long back to an int, use Math.toIntExact, which throws ArithmeticException on overflow instead of wrapping silently.
Decimal separators and grouping
Double.parseDouble("1,5") and Double.parseDouble("1.234,56") both fail. The method expects a dot as the decimal separator and no grouping characters, whatever the default locale of the machine is. For text written for a particular locale, use NumberFormat:
NumberFormat german = NumberFormat.getInstance(Locale.GERMANY);
double value = german.parse("1.234,56").doubleValue(); // 1234.56Two catches apply. NumberFormat.parse throws a checked ParseException, not NumberFormatException. And it stops at the first character it cannot use and returns what it has read so far, so "12abc" parses as 12. When the whole string must be a number, pass a ParsePosition and check that getIndex() equals the length of the input.
Hex, binary and other radixes
Integer.parseInt("ff") fails because the default radix is 10. Pass the radix, or use decode for prefixed literals:
Integer.parseInt("ff", 16); // 255
Integer.parseInt("1010", 2); // 10
Integer.decode("0xff"); // 255, understands the 0x prefixFor a radix other than 10 the message ends with the radix, as in For input string: "zz" under radix 16, which is a useful hint that a caller passed the wrong base.
Inputs and what each method does
| Input | parseInt | Better handling |
|---|---|---|
"42" | 42 | Use as is |
" 42" | Exception | strip() first |
"" | Exception | Check isBlank(), return a default or an error |
null | Exception | Check for null at the boundary |
"1,000" | Exception | Remove grouping or use NumberFormat |
"4.5" | Exception | Parse as double, then decide how to round |
"3000000000" | Exception | Use long |
"٤٢" (Arabic-Indic digits) | 42 | Accepted by Character.digit, which surprises people |
The last row catches validators that use parseInt to decide whether a string is "numeric". If you need ASCII digits only, check with a regular expression such as [0-9]+ before parsing.
Validate before you parse
At an API boundary, do not catch the exception to produce an error message. Declare the type and let validation report it:
record QuantityRequest(@Min(1) @Max(1000) int quantity) { }With Spring MVC, a request parameter that cannot be converted raises MethodArgumentTypeMismatchException, and a JSON body with text in a numeric field raises HttpMessageNotReadableException; see that error. A single exception handler turns both into a 400 with the field name, which is more useful to the caller than a stack trace.
Finding the bad value in a batch
When the failing input is one row among thousands, the exception message is not enough, because it does not say which row. Wrap the parse so the context travels with the error:
static int parseField(String raw, String column, int lineNumber) {
try {
return Integer.parseInt(raw.strip());
} catch (NumberFormatException e) {
throw new IllegalArgumentException(
"line %d, column %s: not a whole number: '%s'".formatted(lineNumber, column, raw), e);
}
}The quotes around %s matter, because they make a trailing space or an empty value visible in the log. Collect the problems in a list and report them together after reading the whole file. A user who learns about one bad row per upload and fixes them one at a time will not thank you, and an operator reading a log wants all of them at once.
Testing the edges
Parsing code earns a small table-driven test, because the interesting inputs are exactly the ones nobody types by hand. Cover the empty string, a string of spaces, a leading plus, the largest and smallest valid values, one more than the largest, a decimal point, a thousands separator and a non-breaking space. Seven or eight rows find every bug in this post, and the test documents what your parser accepts, which is what the next developer needs to know before changing it.
Related exceptions
Boolean.parseBoolean never throws, and returns false for anything other than "true", ignoring case. UUID.fromString throws IllegalArgumentException, and LocalDate.parse throws DateTimeParseException. For a file with a fixed format, validate the whole line with a regular expression before splitting, so a bad token produces one clear error with the line number. The accepted grammar is spelled out in the [Integer.parseInt documentation](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Integer.html), and [NumberFormat](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/text/NumberFormat.html) covers locale-aware parsing. For its neighbours in the runtime exception family, see [ArrayIndexOutOfBoundsException](/library/arrayindexoutofboundsexception-fix-indexoutofbounds).


