Which Scanner Class Method Reads an Int?

If you have ever worked with Java, you have almost certainly asked yourself: which Scanner class method reads an int? The answer is nextInt(), and understanding how it works — along with its quirks, limitations, and best practices — can save you hours of debugging. The Scanner class is one of Java's most frequently used tools for reading user input, and knowing exactly how it handles integer values is a foundational skill for any developer. In this guide we break down everything you need to know, from basic syntax to advanced input validation, so you can write cleaner, more reliable Java programs.

Whether you are a student writing your first console app or a professional brushing up on standard I/O, this deep dive into Scanner.nextInt() covers every angle. We also look at related methods, common pitfalls, and how to handle edge cases gracefully. If you have ever wondered whether a scanner is input or output, the short answer in the Java world is firmly input — and nextInt() is one of the primary ways it fulfills that role.

Understanding the Java Scanner Class

What Is java.util.Scanner?

The Java Scanner class, found in the java.util package, is a text parser that can read primitive types and strings from a variety of input sources. Those sources include System.in (keyboard input), files, strings, and any InputStream or Readable object. Under the hood, Scanner uses a delimiter pattern — by default any whitespace — to break the incoming token stream into pieces it can interpret as specific data types.

To use Scanner, you must first import it and instantiate it with a source:

import java.util.Scanner;

Scanner sc = new Scanner(System.in);

That single object now gives you access to more than a dozen next*() methods, each tailored to a particular data type. The class was introduced in Java 5 and remains the go-to for introductory console I/O because it requires no boilerplate around BufferedReader or InputStreamReader.

How Scanner Reads from Input Streams

Scanner does not read character by character. It buffers input and splits it into tokens based on the active delimiter. When you call a next*() method, Scanner skips any delimiter characters (whitespace by default), then reads tokens until it hits the next delimiter or the end of the stream. If the token it finds cannot be interpreted as the requested type, it throws an exception rather than silently returning a default value — a design choice that encourages explicit error handling.

This token-based approach is part of why Scanner is so convenient: a user can type 42 17 8 on a single line, and three successive calls to nextInt() will each return one of those numbers without any manual string parsing on your part.

How do you read an int Scanner?
How do you read an int Scanner?

Which Scanner Class Method Reads an Int? — nextInt() Explained

The direct answer: nextInt() is the Scanner class method that reads an int. When called, it scans the next token of the input as an int value and returns it. Internally it uses a regular expression to match the token against the pattern for a valid integer in the current locale and the current radix (base 10 by default). If the match succeeds, the token is consumed and the integer value is returned. If it fails, the token is left in the buffer and an InputMismatchException is thrown.

Syntax and Basic Usage

The method signature is simple:

public int nextInt()
public int nextInt(int radix)

The no-argument version reads in base 10. The overloaded version accepts a radix so you can read hexadecimal (16), octal (8), or binary (2) input directly without converting strings yourself. Both versions return a primitive int, not an Integer wrapper, so there is no unboxing overhead.

Key characteristics:

  • Skips leading whitespace before scanning the token.
  • Does not consume the trailing newline character after the integer — this is the most common source of bugs when mixing nextInt() with nextLine().
  • Respects the Scanner's locale for digit grouping symbols (e.g., commas in some locales).
  • Blocks until input is available when reading from System.in.

A Complete Code Example

The snippet below shows a minimal but complete program that demonstrates nextInt() in action, including a loop that reads multiple integers and sums them:

import java.util.Scanner;

public class SumIntegers {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int sum = 0;
        int count = 0;

        System.out.println("Enter integers (type 'done' to finish):");

        while (sc.hasNextInt()) {
            sum += sc.nextInt();
            count++;
        }

        sc.close();
        System.out.printf("Sum of %d integers: %d%n", count, sum);
    }
}

Notice the use of hasNextInt() as a guard. This companion method returns true if the next token can be interpreted as an int, letting you exit the loop cleanly when non-integer input arrives instead of crashing with an exception. The pairing of hasNextInt() + nextInt() is the idiomatic way to read integers safely in Java.

Comparing All Scanner Read Methods

Methods by Data Type

Scanner provides a symmetrical set of methods for every Java primitive type, plus strings. Understanding where nextInt() fits in the full picture helps you choose the right tool when your data type changes.

Method Return Type Has Companion? Radix Variant? Notes
nextInt() int hasNextInt() Yes Primary method for reading integer values; does not consume newline
nextLong() long hasNextLong() Yes Use when values may exceed Integer.MAX_VALUE (2,147,483,647)
nextDouble() double hasNextDouble() No Reads decimal numbers; locale-sensitive decimal separator
nextFloat() float hasNextFloat() No Lower precision than nextDouble(); rarely preferred
nextBoolean() boolean hasNextBoolean() No Accepts "true" / "false" (case-insensitive)
nextShort() short hasNextShort() Yes Range: −32,768 to 32,767
nextByte() byte hasNextByte() Yes Range: −128 to 127
next() String hasNext() No Reads one whitespace-delimited token as a string
nextLine() String hasNextLine() No Reads entire line including spaces; does consume newline

Notice that nextInt(), nextLong(), nextShort(), and nextByte() all support a radix argument, making them the integer-family methods. All other primitive-type methods parse in a fixed format determined by locale.

The Radix Variant of nextInt()

The overloaded nextInt(int radix) is underused but powerful. Suppose you are parsing network protocol data where values are transmitted in hexadecimal. Instead of reading the token as a string and calling Integer.parseInt(token, 16), you can simply do:

Scanner sc = new Scanner("FF 1A 0B");
sc.useRadix(16);
int first = sc.nextInt();  // returns 255
int second = sc.nextInt(); // returns 26
int third = sc.nextInt();  // returns 11
sc.close();

Or pass the radix per-call: sc.nextInt(16). The per-call version temporarily overrides the Scanner's default radix without changing it globally, which is useful if your input stream mixes bases.

Common Errors When Reading Integers

InputMismatchException

The most frequently encountered error when using nextInt() is java.util.InputMismatchException. This runtime exception is thrown when the next token does not match the integer pattern. Common triggers include:

  • The user types a decimal number like 3.14 when an integer is expected.
  • The user presses Enter on an empty line (empty string is not an integer).
  • Locale mismatch — on some systems, 1,000 with a comma is a valid integer token, but on others it is not.
  • The value is too large for an int (use nextLong() instead).

The safest pattern is to wrap nextInt() in a try-catch and call sc.next() in the catch block to consume and discard the offending token before prompting the user again:

while (true) {
    try {
        System.out.print("Enter a number: ");
        int n = sc.nextInt();
        // use n
        break;
    } catch (InputMismatchException e) {
        System.out.println("Invalid input. Please enter a whole number.");
        sc.next(); // discard bad token
    }
}

Resource Leak and Scanner Closing

IDEs and static analysis tools often flag a warning about a resource leak when Scanner is never closed. Because Scanner implements AutoCloseable, best practice is to wrap it in a try-with-resources block:

try (Scanner sc = new Scanner(System.in)) {
    int value = sc.nextInt();
    System.out.println("You entered: " + value);
}

One important caveat: closing a Scanner that wraps System.in also closes System.in. If your program needs to read from standard input again later, you cannot reopen it. For long-running applications, it is sometimes intentional to keep the Scanner open for the lifetime of the program rather than closing it after each use. Weigh the resource-leak warning against the architecture of your specific application before deciding which approach suits you best.

Best Practices for Using nextInt()

Validating Input Before Reading

The hasNextInt() method is Scanner's built-in validator. It peeks at the next token without consuming it and returns a boolean indicating whether nextInt() would succeed. Using it before every call to nextInt() is the cleanest way to avoid exceptions in production code:

System.out.print("Enter your age: ");
if (sc.hasNextInt()) {
    int age = sc.nextInt();
    if (age >= 0 && age <= 150) {
        System.out.println("Age recorded: " + age);
    } else {
        System.out.println("Age out of realistic range.");
    }
} else {
    System.out.println("That is not a valid integer.");
    sc.next(); // consume the invalid token
}

This pattern — check with hasNextInt(), then call nextInt(), then validate the value's range — covers the three main failure modes: wrong type, out of range, and empty input.

The Newline Character Trap

The single most confusing behavior of nextInt() is that it does not consume the newline character at the end of the line. When the user types 42 and presses Enter, the input buffer contains 42\n. After nextInt() returns 42, the \n is still sitting in the buffer. The very next call to nextLine() will return an empty string because it immediately hits that leftover newline.

The fix is a throw-away nextLine() call after nextInt() whenever you intend to read a full line next:

int age = sc.nextInt();
sc.nextLine(); // consume leftover newline
System.out.print("Enter your name: ");
String name = sc.nextLine(); // now reads correctly

Forgetting this step is the cause of countless "empty string" bugs in beginner Java programs. Bookmark it, because you will encounter it in nearly every program that mixes nextInt() with nextLine().

Beyond console I/O, understanding how data flows in and out of your programs connects to a broader appreciation of tech hardware. Just as Java's Scanner mediates between raw byte streams and typed data, physical scanners mediate between the real world and digital systems. If you are curious about how legal and practical considerations affect real-world scanner use, the post on whether it is illegal to have a police scanner offers an interesting parallel look at scanning from a hardware and legal angle. And if you want to explore dedicated scanner hardware in more depth, the Faro Scanner production guide is a fascinating look at industrial-grade scanning technology.

Frequently Asked Questions

Which Scanner class method reads an int in Java?

The nextInt() method is the Scanner class method that reads an int. It scans the next token from the input stream, interprets it as a base-10 integer by default, and returns a primitive int value. You can also call nextInt(int radix) to read integers in other bases such as hexadecimal or binary.

What is the difference between nextInt() and nextLine() in Scanner?

nextInt() reads the next whitespace-delimited token and interprets it as an integer, leaving the trailing newline in the buffer. nextLine() reads everything up to and including the next newline character and returns the content as a String. When you mix the two methods, you must call a throw-away nextLine() after nextInt() to consume the leftover newline before reading a full line.

What exception does nextInt() throw on bad input?

nextInt() throws java.util.InputMismatchException when the next token cannot be parsed as an integer. It also throws java.util.NoSuchElementException if the input is exhausted and java.lang.IllegalStateException if the Scanner has been closed. Always guard calls with hasNextInt() or a try-catch block to handle these cases gracefully.

How do I read multiple integers on one line with Scanner?

Because nextInt() skips whitespace between tokens, you can call it multiple times in a row on the same line of input. For example, if the user types 10 20 30, three successive calls to sc.nextInt() will return 10, 20, and 30 respectively. Use hasNextInt() in a loop to read an unknown number of integers without hardcoding the count.

Should I close the Scanner after calling nextInt()?

Yes, you should close the Scanner when you are done with it to release system resources. The preferred approach is a try-with-resources block, which closes the Scanner automatically. However, be aware that closing a Scanner wrapping System.in also closes the standard input stream, making it unavailable for the rest of the program's lifetime. For short programs that exit immediately after reading, this is rarely a problem.

Can nextInt() read hexadecimal or binary numbers?

Yes. The overloaded version nextInt(int radix) accepts a radix argument, so sc.nextInt(16) reads a hexadecimal token and returns its decimal integer value, and sc.nextInt(2) reads a binary token. You can also call sc.useRadix(16) to change the default radix for all subsequent calls on that Scanner instance, which is convenient when parsing data files that use a consistent non-decimal format.

About Rachel Chen

Rachel Chen writes about scanners, laminators, and home office productivity gear. She started her career as an office manager at a midsize law firm, where she was responsible for purchasing and maintaining all of the document handling equipment for a 60-person staff. That experience sparked a deep interest in archival workflows, paperless office setups, and document preservation. Rachel later earned a bachelor degree in information science from Rutgers University and now writes full time. She is a strong advocate for ADF reliability over raw resolution numbers and has tested every major flatbed and document scanner sold in the United States since 2018.

Check the FREE Gifts here. Or latest free books from our latest works.

Remove Ad block to reveal all the secrets. Once done, hit a button below