Java Scanner Class

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

Definition and Usage

In Java, java.util.Scanner (since Java 5) reads text from a source and breaks it into tokens using a regular-expression delimiter (whitespace by default). You can read words with next(), whole lines with nextLine(), or numbers and booleans directly with nextInt(), nextDouble(), and nextBoolean().

A Scanner works the exact same way whether the text comes from System.in (keyboard), a String literal, or a file/Path. Always check with lookahead methods such as hasNextInt() when input might not match, because a failed read throws InputMismatchException without consuming the bad token. Browse all 36 guides in the Scanner Methods index.

Not thread-safe and not for bulk high-speed input.

Scanner is designed for convenience and small-to-medium parsing, not multiple threads sharing one scanner or reading millions of lines under tight time limits (where BufferedReader is typically faster because it skips regex matching).

Java Syntax

Import java.util.Scanner, create a scanner around your source, and read tokens or lines:

Java
import java.util.Locale;
import java.util.Scanner;

Scanner sc = new Scanner("Ada 42 9.5").useLocale(Locale.US);
String word = sc.next();            // "Ada"
int count = sc.nextInt();           // 42
double score = sc.nextDouble();     // 9.5
sc.close();

Input Sources and Closing Rules

Create a scanner over whichever text source your program needs:

ConstructorReads fromClosing rule
new Scanner(System.in)Keyboard / standard inputCreate once; closing it also closes System.in for the JVM
new Scanner("a 1 2")An in-memory StringSafe and ideal with try (Scanner sc = ...)
new Scanner(path, "UTF-8")A file via Path (Java 7+) or FileAlways wrap in try-with-resources so the file handle closes
new Scanner(reader)Any Readable or InputStreamclose() closes the source if it implements Closeable

The Classic nextInt() / nextLine() Newline Pitfall

Token methods like nextInt(), nextDouble(), and next() stop right before the trailing whitespace or newline. If you call nextLine() right after nextInt() on "25 Anna Smith", nextLine() reads the empty remainder of line 1 ("") instead of "Anna Smith"! Fix it in one of two ways: call an extra sc.nextLine() to clear the leftover newline, or read every input as a line with sc.nextLine() and parse numbers with Integer.parseInt(line.trim()).

Scanner vs Console vs BufferedReader

Pick the input tool that matches your task:

FeatureScannerConsoleBufferedReader
Works in IDEs and with files/stringsYesSystem.console() may be nullYes
Built-in number parsingYes (nextInt, nextDouble)No (parse strings yourself)No (parse strings yourself)
Hidden password inputNoYes (readPassword)No
Checked exceptionsNo (hides IOException; check ioException())Throws unchecked IOErrorMethods declare IOException
Speed on huge inputsModerate (regex tokenization)Terminal use onlyFast (buffered lines, low overhead)

Delimiters, Locale, and Radix

By default, Scanner splits on p{javaWhitespace}+ (delimiter()), uses radix 10 (radix()), and uses the JVM's default format locale(). Change the separator with useDelimiter() (e.g. "\s*,\s*" for CSV), force dot decimals with useLocale()(Locale.US), switch number bases with useRadix(), or restore all three defaults at once with reset().

Java Examples

Example 1 — Parse a Name, Age, and Score from One Scanner

Scanner works identically whether the source is System.in or a String literal. Here a String supplies deterministic input, and useLocale(Locale.US) ensures 3.75 parses with a dot.

Java
import java.util.Locale;
import java.util.Scanner;

public class ScannerHubBasics {
    public static void main(String[] args) {
        String input = "Anna 25 3.75\nComputer Science";
        try (Scanner sc = new Scanner(input).useLocale(Locale.US)) {
            String name = sc.next();
            int age = sc.nextInt();
            double gpa = sc.nextDouble();
            sc.nextLine();
            String major = sc.nextLine();
            System.out.println("Name: " + name + ", Age: " + age);
            System.out.println("GPA: " + gpa + ", Major: " + major);
        }
    }
}

How It Works

  1. Try-with-resources and Locale.US. Opening the string scanner inside try (...) guarantees close() runs at the end, and useLocale(Locale.US) makes sure 3.75 parses with a dot on every machine.
  2. Token reads stop before the line break. next() takes "Anna", nextInt() takes 25, and nextDouble() takes 3.75, leaving the newline before "Computer Science".
  3. Clear the newline, then read the line. The extra sc.nextLine() consumes the empty remainder of line 1 so the second nextLine() reads "Computer Science".

Example 2 — Sum Numbers Safely and Skip Non-Numeric Tokens

Checking with hasNextInt() before calling nextInt() prevents crashes, and calling next() discards non-number tokens when they appear.

Java
import java.util.Scanner;

public class ScannerHubValidate {
    public static void main(String[] args) {
        String data = "15 skip 25 oops 10";
        int sum = 0;
        int skipped = 0;
        try (Scanner sc = new Scanner(data)) {
            while (sc.hasNext()) {
                if (sc.hasNextInt()) {
                    sum += sc.nextInt();
                } else {
                    System.out.println("Ignoring: " + sc.next());
                    skipped++;
                }
            }
        }
        System.out.println("Sum = " + sum + ", ignored = " + skipped);
    }
}

How It Works

  1. Outer loop over every token. sc.hasNext() keeps the loop going until all five whitespace-separated tokens are handled.
  2. Look ahead without consuming. sc.hasNextInt() returns true for 15, 25, and 10, which are consumed by sc.nextInt() and added into sum.
  3. Advance past bad tokens. For "skip" and "oops", hasNextInt() is false, so sc.next() consumes the word and avoids an infinite loop.

Example 3 — Read User Name and Age from the Keyboard (System.in)

For interactive keyboard input, wrap System.in once in main and do not close the scanner if other code still reads from standard input. Here the user types two lines.

Java
import java.util.Scanner;

public class ScannerHubKeyboard {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your age:");
        int age = sc.nextInt();
        sc.nextLine();
        System.out.println("Enter your full name:");
        String fullName = sc.nextLine();
        System.out.println(fullName + " is " + age + " years old.");
    }
}

How It Works

  1. Keep System.in open when shared. Wrapping System.in in try (...) or calling sc.close() closes standard input for the entire program, so a single long-lived scanner avoids accidental closure.
  2. Discard the Enter key after nextInt(). Typing 21 and pressing Enter leaves a newline in the buffer; sc.nextLine() clears it before prompting for the name.
  3. Read the full name with spaces. The second sc.nextLine() reads "Maya Patel" up to the Enter key, keeping the space between first and last name.

Next: Java Scanner Methods by Group

Full list with short descriptions: Java Scanner Methods index.

Frequently Asked Questions

java.util.Scanner (since Java 5) is a text scanner that splits input from System.in, a String, a File/Path, or a Readable into tokens using a regex delimiter (whitespace by default) and parses primitives and strings.
nextInt() reads only the digits and stops right before the newline character left when you pressed Enter. Calling nextLine() immediately reads the rest of that same line, which is empty. Call an extra sc.nextLine() to consume it first.
Be careful: closing a Scanner also closes its underlying stream if it is Closeable. Closing a Scanner on System.in closes System.in for the rest of your program, so future Scanners on System.in will fail to read anything.
Scanner parses numbers using its current Locale. In German or French locales, decimals use a comma (3,5) instead of a dot (3.5). Call sc.useLocale(Locale.US) when your input uses dot decimals.
Use BufferedReader when reading huge files or millions of lines quickly, because Scanner does regex parsing and has higher overhead. Use java.io.Console when you need hidden password input in a terminal.

Browse every Scanner method

Open the methods index for categorized guides with runnable examples and FAQs.

Scanner Methods Index →

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.

9 people found this page helpful