Java Scanner close() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.Scanner

Definition

In Java, sc.close() closes the scanner. If the underlying source implements java.io.Closeable (such as a file, stream, or Reader), closing the scanner closes that underlying source as well.

Calling close() more than once is idempotent (subsequent calls do nothing), while calling reading or setter methods on a closed scanner throws IllegalStateException.

An instance method of java.util.Scanner, available since Java 5 (JDK 1.5). A Scanner reads from any source (System.in for keyboard, a String, or a file) with identical parsing logic; pass the source to new Scanner(...) after import java.util.Scanner; and call sc.close(...).

Syntax

Prefer try-with-resources for strings, files, and readers so close() runs automatically.

Java
try (Scanner sc = new Scanner("10 20")) {
    int sum = sc.nextInt() + sc.nextInt();
}   // sc.close() called automatically here
CallWhat it does
sc.close()Closes the scanner and closes its underlying Closeable source.
try (Scanner sc = new Scanner(...))Automatically closes sc when leaving the block.

Because Scanner implements Closeable (and AutoCloseable), try (Scanner sc = ...) works in Java 7 and later.

Library declarations
Java
// java.util.Scanner
public void close()

Parameters

ParameterDescription
Noneclose() takes no parameters.

Return Value

Return ValueDescription
voidReturns nothing. Safe to call multiple times (idempotent).

Compare with Similar Methods

Closing resources safely:

MethodHow it differs
ioException()Retrieves any IOException suppressed during close().
reset()Resets settings on an open scanner (throws if closed).
Console.reader()Shared console reader that should likewise not be closed early.

Java Examples

Example 1 — Close Safely with Try-With-Resources and Verify Idempotence

Close a scanner twice (no error), then confirm that calling next() or hasNext() throws IllegalStateException.

Java
import java.util.Scanner;

public class ScannerCloseIdempotent {
    public static void main(String[] args) {
        Scanner sc = new Scanner("10 20");
        System.out.println("First: " + sc.nextInt());
        sc.close();
        sc.close();
        System.out.println("Closed twice without error.");
        try {
            sc.nextInt();
        } catch (IllegalStateException e) {
            System.out.println("Read after close: " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Read before closing. sc.nextInt() consumes 10 while the scanner is still open.
  2. Second close() is a no-op. Calling close() twice is guaranteed idempotent and never fails.
  3. Subsequent operations fail loudly. Calling nextInt() on a closed scanner throws IllegalStateException.

Example 2 — Observe Scanner.close() Closing Its Underlying Closeable Source

Wrap a custom Closeable reader inside try-with-resources to prove Scanner.close() closes the source too.

Java
import java.io.Closeable;
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.Scanner;

public class ScannerCloseSource {
    static class TrackedReader implements Readable, Closeable {
        boolean sent = false;
        public int read(CharBuffer cb) {
            if (sent) return -1;
            sent = true;
            cb.append("42");
            return 2;
        }
        public void close() throws IOException {
            System.out.println("Underlying source closed!");
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(new TrackedReader());
        try {
            System.out.println("Value: " + sc.nextInt());
        } finally {
            sc.close();
        }
    }
}

How It Works

  1. Source implements Closeable. TrackedReader prints a trace message when its close() method runs.
  2. Guaranteed cleanup in finally. Putting sc.close() inside finally ensures closing happens even if reading fails.
  3. Scanner forwards close to source. Because TrackedReader is Closeable, Scanner closes it too.

Example 3 — Keep One Scanner(System.in) Open Instead of Closing Early

Use one shared keyboard scanner in main so System.in stays open across multiple prompts.

Java
import java.util.Scanner;

public class ScannerCloseKeyboard {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter first score:");
        int first = sc.nextInt();
        System.out.println("Enter second score:");
        int second = sc.nextInt();
        System.out.println("Combined score: " + (first + second));
        sc.close();
    }
}

How It Works

  1. Single shared System.in scanner. Keeping one scanner open across all prompts prevents closing standard input mid-program.
  2. Two sequential reads succeed. Both 40 and 55 are read smoothly from the same open stream.
  3. Close only when all input is done. Calling sc.close() at the very end of main shuts down System.in only after nothing else needs it.

Frequently Asked Questions

Do not close it inside helper methods or if any code still needs System.in, because sc.close() closes System.in permanently for the running JVM.
Scanner throws IllegalStateException ("Scanner closed").
Yes. close() is idempotent, so calling it a second time has no effect and does not throw.
Yes. If the source passed to the Scanner constructor implements Closeable, sc.close() closes it too.
Using try (Scanner sc = new Scanner("...")) is harmless and good practice, even though a String itself holds no OS handle.

Next: delimiter()

Return the Pattern the scanner currently uses to split tokens.

delimiter() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P πŸ”—

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful