java.lang.NumberFormatException in Java
java.lang.NumberFormatException means Java tried to convert a String into a numeric value, but the string was not valid for the numeric type being requested. A common example is calling Integer.parseInt("25k"), where the letter k makes the input invalid for an integer.
To fix NumberFormatException, first inspect the exact input string shown in the error message, then decide whether the input should be rejected, cleaned, converted with a different parser, or handled with a fallback value. This tutorial recreates the exception, explains the stack trace, and shows safe ways to handle values such as N/A, blank strings, decimal strings, formatted numbers, and numbers outside the range of int.
Java methods that can throw NumberFormatException while parsing strings
The exception is thrown by many constructors and methods in the classes of the java.lang package. Following are some of them:
- public Byte(String s) throws NumberFormatException (java doc link)
- public static byte parseByte(String s, int radix) throws NumberFormatException
- public static byte parseByte(String s) throws NumberFormatException
- public static Byte valueOf(String s, int radix) throws NumberFormatException
- public static Byte valueOf(String s) throws NumberFormatException
- public Integer(String s) throws NumberFormatException
- public static int parseInt(String s) throws NumberFormatException
In new Java code, prefer parser methods such as Integer.parseInt(), Long.parseLong(), Double.parseDouble(), and BigDecimal construction instead of wrapper constructors such as new Integer(String). The parser should match the kind of value you expect.
int quantity = Integer.parseInt("25");
long count = Long.parseLong("9223372036854775807");
double price = Double.parseDouble("16.0");
When Integer.parseInt throws NumberFormatException
There are situations defined for each parsing method where it can throw a NumberFormatException. For instance, public static int parseInt(String s) throws NumberFormatException can fail when:
- The input string is
nullor has length zero. - The string contains characters that are not valid digits for the parser, such as
"25k","N/A","1,000", or whitespace around the number. - The value is not valid for the requested numeric type. For example,
"16.0"is valid forDouble.parseDouble(), but not forInteger.parseInt(). - The value is outside the range of the target type. For example, a number larger than
Integer.MAX_VALUEcannot be parsed as anint. - The radix is invalid, or the digits do not match the specified radix.
Reproducing NumberFormatException for input string “25k”
Let us investigate deeper as to how this exception comes into picture, by running the following program.
NumberFormatExceptionExample.java
package com.mm;
/**
* @author tutorialkart.com
*/
public class NumberFormatExceptionExample {
public static void main(String[] args){
int i = Integer.parseInt("25k");
System.out.println(i);
}
}
We get the following Java call stack in console as output.
Output
Exception in thread "main" java.lang.NumberFormatException: For input string: "25k"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at com.mm.NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:8)
The important part of the message is For input string: "25k". It tells us the exact value that Java could not convert into an integer. In real applications, this value may come from a form field, CSV file, database column, API response, command-line argument, or configuration file.
Reading the NumberFormatException stack trace from bottom to top
We shall go into the stack and analyze one method after another, from the bottom of the call stack. Line numbers can vary by JDK version, but the flow is the same: your code calls Integer.parseInt(), and parseInt() rejects the invalid character.
at com.mm.NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:8):
7: public static void main(String[] args){
8: int i = Integer.parseInt("25k");
9: System.out.println(i);
10:}
at java.lang.Integer.parseInt(Integer.java:527) :
Integer.parseInt(“25k”)
526: public static int parseInt(String s) throws NumberFormatException {
527: return parseInt(s,10);
528: }
at java.lang.Integer.parseInt(Integer.java:492) :
parseInt(s,10)
444: public static int parseInt(String s, int radix)
445: throws NumberFormatException
446: {
447: /*
448: * WARNING: This method may be invoked early during VM initialization
449: * before IntegerCache is initialized. Care must be taken to not use
450: * the valueOf method.
451: */
452:
453: if (s == null) {
454: throw new NumberFormatException("null");
455: }
456:
457: if (radix < Character.MIN_RADIX) { 458: throw new NumberFormatException("radix " + radix + 459: " less than Character.MIN_RADIX"); 460: } 461: 462: if (radix > Character.MAX_RADIX) {
463: throw new NumberFormatException("radix " + radix +
464: " greater than Character.MAX_RADIX");
465: }
466:
467: int result = 0;
468: boolean negative = false;
469: int i = 0, len = s.length();
470: int limit = -Integer.MAX_VALUE;
471: int multmin;
472: int digit;
473:
474: if (len > 0) {
475: char firstChar = s.charAt(0);
476: if (firstChar < '0') { // Possible leading "+" or "-"
477: if (firstChar == '-') {
478: negative = true;
479: limit = Integer.MIN_VALUE;
480: } else if (firstChar != '+')
481: throw NumberFormatException.forInputString(s);
482:
483: if (len == 1) // Cannot have lone "+" or "-"
484: throw NumberFormatException.forInputString(s);
485: i++;
486: }
487: multmin = limit / radix;
488: while (i < len) {
489: // Accumulating negatively avoids surprises near MAX_VALUE
490: digit = Character.digit(s.charAt(i++),radix);
491: if (digit < 0) {
492: throw NumberFormatException.forInputString(s);
493: }
494: if (result < multmin) {
495: throw NumberFormatException.forInputString(s);
496: }
497: result *= radix;
498: if (result < limit + digit) {
499: throw NumberFormatException.forInputString(s);
500: }
501: result -= digit;
502: }
503: } else {
504: throw NumberFormatException.forInputString(s);
505: }
506: return negative ? result : -result;
507: }
In the example input "25k", the loop reads 2 and 5 successfully. When it reaches k, Character.digit() returns a negative value for base 10, and parseInt() throws NumberFormatException.
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) :
NumberFormatException.forInputString(s);
64: static NumberFormatException forInputString(String s) {
65: return new NumberFormatException("For input string: \"" + s + "\"");
66: }
This is the string For input string: "25k" at the top of our call stack. We reached it by digging from the bottom of the call stack.
How to handle java.lang.NumberFormatException safely
Use a try-catch block around the code that could cause NumberFormatException. Catch it close to the place where external or untrusted input is parsed, so you can show a useful validation message or apply a safe fallback.
NumberFormatExceptionHandlingExample.java
/**
* @author tutorialkart.com
*/
public class NumberFormatExceptionHandlingExample {
public static void main(String[] args){
try {
int i = Integer.parseInt("25k");
System.out.println(i);
} catch (NumberFormatException e) {
System.out.println("NumberFormatException is handled");
}
}
}
We have seen in the “How is it caused” section above, that forInputString() method returns an object of type NumberFormatException.
FYR : 65: return new NumberFormatException(“For input string: \”” + s + “\””);
This object of type java.lang.NumberFormatException contains the details collected by JVM for the cause of exception and relevant messages.
When the above example program is run, you will get the following output.
Output
NumberFormatException is handled
Another way of handling the exception is the use of the throws keyword. The method definition should be modified as shown in the following example.
NumberFormatExceptionHandlingExample.java
/**
* @author tutorialkart.com
*/
public class NumberFormatExceptionHandlingExample {
public static void main(String[] args){
try {
new NumberFormatExceptionHandlingExample().intParsingMethod();
} catch (NumberFormatException e) {
System.out.println("NumberFormatException is handled");
}
}
public void intParsingMethod() throws NumberFormatException{
int i = Integer.parseInt("25k");
System.out.println(i);
}
}
Output
NumberFormatException is handled
Here, method intParsingMethod() throws the exception object that is thrown by Integer.parseInt("25k") to its calling method, which is main() in this case.
Using throws does not fix invalid input by itself. It only passes the exception to the caller. Use it when the current method cannot decide what to do with the bad value, and make sure the caller handles the exception.
How to avoid NumberFormatException before parsing user input
If the input comes from a user, file, network, or database, validate it before parsing. A safe parser usually follows these steps:
- Check for
nullbefore callingtrim(). - Trim leading and trailing whitespace when spaces are not meaningful.
- Reject known non-number values such as
N/A,-, or an empty string. - Use a regular expression or field-level validation to allow only the numeric format your program accepts.
- Still keep a try-catch block for overflow, underflow, and unexpected input.
The following method returns an empty result instead of throwing NumberFormatException to the caller.
import java.util.OptionalInt;
public class SafeIntegerParser {
public static OptionalInt parseWholeNumber(String value) {
if (value == null) {
return OptionalInt.empty();
}
String text = value.trim();
if (!text.matches("[+-]?\\d+")) {
return OptionalInt.empty();
}
try {
return OptionalInt.of(Integer.parseInt(text));
} catch (NumberFormatException ex) {
return OptionalInt.empty(); // value is outside the int range
}
}
}
This approach is useful when bad input is expected and should be treated as a validation failure, not as a program crash.
Common NumberFormatException messages and practical fixes
| Input or message | Why it fails | Practical fix |
|---|---|---|
For input string: "25k" | The input contains a non-digit character for base 10 integer parsing. | Reject it, or separate the number from the unit before parsing. |
For input string: "N/A" | N/A is a placeholder, not a number. | Treat it as missing data before calling a parser. |
For input string: "" | The string is empty after reading or trimming. | Check for blank input and show a validation message. |
For input string: "16.0" | Integer.parseInt() does not accept decimal points. | Use Double.parseDouble(), BigDecimal, or convert only after checking that a decimal value is expected. |
For input string: "1,000" | The comma is not valid for Integer.parseInt(). | Remove grouping separators only when your input format allows them. |
For input string: "999999999999" | The value is too large for int. | Use Long.parseLong(), BigInteger, or reject the value as out of range. |
Choosing parseInt, parseLong, parseDouble, BigInteger, or BigDecimal
A frequent cause of NumberFormatException is using the wrong parser for the data. Choose the parser based on the format and range you need.
| Expected value | Parser to consider | Example input |
|---|---|---|
Whole number in int range | Integer.parseInt() | "25" |
Whole number larger than int range but within long range | Long.parseLong() | "5000000000" |
| Very large whole number | BigInteger | "123456789012345678901234567890" |
| Decimal value | Double.parseDouble() or BigDecimal | "16.0" |
| Money or exact decimal arithmetic | BigDecimal | "199.99" |
| Binary, octal, or hexadecimal text | Integer.parseInt(value, radix) | "FF" with radix 16 |
For formatted numbers such as "1,234", do not remove characters blindly. First define the accepted input format. For example, removing all commas is fine for a controlled integer field, but it may be wrong for data that uses a comma as a decimal separator in some locales.
Fixing NumberFormatException in real Java input flows
Most NumberFormatException errors are not caused by the parser itself. They are caused by a mismatch between the input source and the parser. Use these checks before changing code:
- Form input: confirm that the field is required, trimmed, and validated before conversion.
- CSV or text file: print the raw token with quotes so hidden spaces and empty values are visible.
- API response: check whether the field can contain
null,N/A, or a decimal string. - Database value: verify whether the column is actually numeric or stored as formatted text.
- Android input field: do not assume the keyboard restriction is enough; validate the string before parsing.
When debugging, log the value with delimiters before parsing:
String input = " 25 ";
System.out.println("Input before parsing = [" + input + "]");
int number = Integer.parseInt(input.trim());
The square brackets make leading spaces, trailing spaces, and empty strings easier to notice in logs.
FAQ on java.lang.NumberFormatException
What is the message of NumberFormatException in Java?
The most common message is java.lang.NumberFormatException: For input string: "value". The value inside the quotes is the exact string that Java failed to parse. Other messages can mention null or an invalid radix, depending on the parser and input.
How do I avoid NumberFormatException in Java?
Validate the string before parsing, check for null and blank values, use the correct parser for the expected number type, and catch NumberFormatException around external input. Do not assume that user input, file data, or API data is already numeric.
Why does Integer.parseInt(“16.0”) throw NumberFormatException?
Integer.parseInt() accepts whole-number text only. The decimal point in "16.0" makes it invalid for an integer parser. Use Double.parseDouble("16.0") or BigDecimal when the value is meant to be decimal.
Should I catch NumberFormatException or validate first?
Use both when the input is external. Validation gives a cleaner user message and prevents expected bad values from becoming exceptions. The catch block is still useful because very large values, unexpected formats, or race conditions can still reach the parser.
Is NumberFormatException a checked exception?
No. NumberFormatException is an unchecked exception because it extends IllegalArgumentException, which extends RuntimeException. Java does not force you to catch or declare it, but you should handle it where invalid input is expected.
Editorial QA checklist for this NumberFormatException tutorial
- Confirm every new code block uses the correct PrismJS class:
language-java,language-java syntax, oroutput. - Verify that examples distinguish whole numbers, decimal numbers, formatted numbers, missing values, and out-of-range values.
- Keep the stack trace explanation tied to the actual
"25k"input used in the original example. - Check that handling advice does not hide invalid data silently in business-critical flows.
- Ensure FAQ answers are specific to
java.lang.NumberFormatException, not generic Java exception handling.
NumberFormatException fix summary
In this Java Tutorial, we have learnt how java.lang.NumberFormatException occurs and how to fix it using validation, the correct parser, and Java Try Catch. Start with the exact string shown in the exception message, then check whether the input is blank, non-numeric, decimal, formatted, or outside the allowed range.
TutorialKart.com