Free: 4 trials of 20 minutes, no cardStart free

Craftstack Academy
Java

Java NumberFormatException: For input string, and how to fix it

· 8 min read

Your program asks how many steps you walked today. You press Enter a moment too early, and Java stops:

Terminal
How many steps today? 
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:672)
	at java.base/java.lang.Integer.parseInt(Integer.java:778)
	at Main.main(Main.java:7)

NumberFormatException: For input string: "" means Integer.parseInt was asked to turn text into a whole number, and the text wasn't one. The part in quotes is the exact text it received, and it's the most useful clue in the whole message: here it's "", an empty string, because nothing was typed. This article shows how to read that clue and fix the six usual cases: empty input, decimals, spaces, commas, numbers that are too big, and text that was never a number.

Try it yourself

Save this as Main.java, then run javac Main.java and java Main:

Main.java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("How many steps today? ");
        int steps = Integer.parseInt(scanner.nextLine());
        System.out.println("Steps: " + steps);
    }
}

Type 8000 and it works. Then run it again and try: nothing (press Enter), 3.5, twelve, 42 with a space in front. Each one throws this exception, with different text in the quotes.

What the exception means

Read it in parts:

  • Exception in thread "main": a problem while the program runs. It compiled fine.
  • java.lang.NumberFormatException: the text wasn't in a number format that the method accepts.
  • For input string: "": the exact text it got, between the quotes.
  • The at lines: where it happened. Skip the lines that start with java.base; they're inside Java itself. The first line with your file, at Main.main(Main.java:7), is the one to look at.

Integer.parseInt accepts digits, with an optional + or - in front, and nothing else. So the question is always: why was the text in the quotes not only digits?

Cause 1: empty input, ""

The example above. nextLine() returned an empty string because the user pressed Enter without typing. In a file, the same comes from an empty line, often the last line.

Check before you convert, or ask again (see "The robust fix" below). For a file, skip empty lines:

java
if (line.isBlank()) {
    continue;
}

Cause 2: a decimal number, "3.5"

Terminal
Hours a day? 3.5
Exception in thread "main" java.lang.NumberFormatException: For input string: "3.5"
	...
	at Main.main(Main.java:7)

parseInt reads whole numbers only. If decimals are allowed, use double and Double.parseDouble("3.5"), which gives 3.5. If you need a whole number, convert to double first and cast: (int) Double.parseDouble("3.9") gives 3. The cast cuts off the decimals, it doesn't round. Use Math.round if you want rounding.

Cause 3: spaces and line breaks, " 42"

This one surprises people coming from Python, where int(" 42") works. In Java, parseInt doesn't ignore spaces:

Terminal
For input string: " 42"

Look closely at the quotes: there's a space before 42. The fix is trim(), which removes spaces and line breaks at both ends:

java
int steps = Integer.parseInt(scanner.nextLine().trim());

With trim(), " 42" becomes 42. A line break at the end, "42\n", also fails without trim(). In the message, it shows up as a quote that closes on the next line:

Terminal
For input string: "42
"

(Double.parseDouble is more forgiving: in our test, " 3.5 " with spaces worked. Integer.parseInt is the strict one.)

Cause 4: commas, units and signs, "1,000"

Terminal
For input string: "1,000"

Thousands separators, currency signs and units (€20, 5kg, 3 hours) are all text to parseInt. Clean the text first:

java
int amount = Integer.parseInt(text.replace(",", "").trim());

Be careful with international input: in many countries 1,5 means one and a half. If people from different countries type numbers, decide on one format and tell them.

Cause 5: a number too big for int, "2147483648"

Terminal
For input string: "2147483648"

These are only digits, so why does it fail? An int can hold values up to 2,147,483,647. One more doesn't fit, and parseInt reports it with the same message. For bigger numbers, use long and Long.parseLong, which worked for this value in our test. Phone numbers and card numbers are a common case: store those as String, because you never do maths with them and they can start with 0.

Cause 6: text from the wrong place

Often the text in the quotes isn't a number because it's the wrong piece of data. Two classic examples, both from reading files:

A header row: the first line of a CSV file holds the column names.

java
String header = "name,age";
int age = Integer.parseInt(header.split(",")[1]);
Terminal
Exception in thread "main" java.lang.NumberFormatException: For input string: "age"
	...
	at Main.main(Main.java:4)

The quotes say "age": a column name, not an age. Skip the first line before converting.

A wrong separator: the file uses ; but the code splits on ,.

Terminal
Exception in thread "main" java.lang.NumberFormatException: For input string: "Sam;31"
	...
	at Main.main(Main.java:5)

split(",") found no comma, so the whole line stayed in one piece. The quotes show you exactly that. Split on the character the file really uses.

The robust fix: catch the exception and ask again

For input from people, you can't prevent bad answers, so handle them:

Main.java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int hours;
        while (true) {
            System.out.print("Hours a day? ");
            String text = scanner.nextLine().trim();
            try {
                hours = Integer.parseInt(text);
                break;
            } catch (NumberFormatException e) {
                System.out.println("Please type a whole number, like 3.");
            }
        }
        System.out.println("That is " + hours * 365 + " hours a year.");
    }
}
Terminal
Hours a day? abc
Please type a whole number, like 3.
Hours a day? 
Please type a whole number, like 3.
Hours a day? 7
That is 2555 hours a year.

try runs the conversion. If it throws, the program jumps to catch, prints a friendly message and loops. When it works, break leaves the loop. Catch NumberFormatException specifically, not every exception, so real bugs still show up.

Other wordings of the same exception

The message changes slightly with the method and the input. These came from our test with Java 21:

Terminal
For input string: "twelve"
For input string: "0x1A"
Cannot parse null string
empty String
  • "0x1A": parseInt doesn't read hexadecimal prefixes. Integer.parseInt("1A", 16) gives 26.
  • Cannot parse null string: the variable was null, not text. That's a different bug: the value never arrived. See NullPointerException for tracking down where a null came from.
  • empty String: the message from Double.parseDouble(""). Same cause as cause 1.

Negative numbers and a plus sign are fine: parseInt("-7") and parseInt("+7") both worked.

Errors that look alike

  • incompatible types: String cannot be converted to int: a compile error, when you forget parseInt entirely. See String cannot be converted to int.
  • InputMismatchException: the same problem when you read with scanner.nextInt() instead of nextLine() plus parseInt.
  • Python's ValueError: invalid literal for int() with base 10: the same idea in Python. See invalid literal for int().

Wrong fixes that don't help

  • Catching Exception and ignoring it. The variable keeps no value, and the next error is harder to understand.
  • Removing every character that isn't a digit. "3.5" becomes 35 and "-7" becomes 7.
  • Using scanner.nextInt() to avoid parseInt. It fails on the same input, with a different exception, and leaves the line break behind for the next nextLine().

A debugging walkthrough

A grade program crashes with NumberFormatException: For input string: "Mia":

  1. Read the text in the quotes: "Mia". A name, not a grade.
  2. Find your line in the at lines: the first one with your file name.
  3. Find where the text comes from: which piece of the split, which line of the file, which input?
  4. Fix the source: the right index after split, skip the header, the right separator.
  5. Add trim() and a try/catch for any text that comes from a person or a file.

Practice

What does each print or throw?

  1. Integer.parseInt("007")
  2. Integer.parseInt("7 ")
  3. Integer.parseInt("7 ".trim()) + 1

Answers. (1) 7: leading zeros are fine. (2) NumberFormatException: For input string: "7 ", because of the space. (3) 8.

Frequently asked questions

What does "For input string" mean in Java?

It's the start of the NumberFormatException message. The text after it, in quotes, is what parseInt or parseDouble tried to convert.

How do I fix NumberFormatException: For input string: ""?

The text was empty. Check with isBlank() before converting, skip empty lines in files, or catch the exception and ask again.

Does Integer.parseInt ignore spaces?

No. Use text.trim() first.

How do I convert "3.5" to an int in Java?

(int) Double.parseDouble("3.5") gives 3. Use Math.round(Double.parseDouble("3.5")) to round instead.

Is NumberFormatException a checked exception?

No. It's a runtime exception, so Java doesn't force you to catch it. For user input and files, you should anyway.

A quick checklist

  1. Read the text in the quotes.
  2. Empty? Handle empty input or skip blank lines.
  3. Spaces or a line break? Add trim().
  4. A decimal? Use Double.parseDouble.
  5. Too big? Use long, or keep it as String.
  6. From a person or a file? Catch NumberFormatException.

For a method that works on any error, read how to read an error message. The Java documentation lists exactly what Integer.parseInt) accepts.

1 beginner error a week

One common error, what it means and how to fix it, in a short email. Free, and you can unsubscribe in any email.

Java

Java error: missing return statement, and how to fix it

Why Java says error: missing return statement when your method clearly returns: if without else, a loop that may not return, try/catch and switch. With compiled examples and fixes.

Error explained · · 9 min read

Learn by writing the code yourself.

Twenty minutes with the tutor, right in your browser. No card, nothing to install.

Start the free trial
A session: the tutor's chat on the left, the code editor with a Java program and its output on the right