Java Scanner Class

Su Suriya Ravichandran Updated 18 Nov 2026
11 min read ·Lesson 150 of 306

What Scanner Does

java.util.Scanner reads text and breaks it into tokens — pieces separated by a delimiter, which is whitespace by default — and converts tokens into Java types: nextInt(), nextDouble(), nextBoolean(), nextBigDecimal() and so on. It can read from System.in, a file, a String or any InputStream or Reader.

That makes it the most convenient tool for interactive console programs and for small, simply structured text inputs, where you'd otherwise have to read lines and parse them yourself:

Scanner sc = new Scanner(System.in);
int age = sc.nextInt();        // reads the next token and converts it to int

Its convenience comes at a cost: Scanner uses regular expressions internally and is much slower than BufferedReader for large inputs, and its mix of token-based and line-based methods has a well-known trap (covered below). For big files and fast parsing, use BufferedReader; for interactive input and quick parsing, Scanner is ideal.

Creating a Scanner

Scanner keyboard = new Scanner(System.in);                         // standard input
Scanner file     = new Scanner(Path.of("scores.txt"), StandardCharsets.UTF_8); // a file (throws IOException)
Scanner text     = new Scanner("PEN-01 12 4.50");                  // a String
Scanner encoded  = new Scanner(inputStream, StandardCharsets.UTF_8); // any stream, explicit charset

Constructors without a charset argument — for System.in, a Path or any stream — decode bytes with the platform default charset. That is UTF-8 everywhere since Java 18, but on Java 17 and earlier it depended on the operating system, so pass a charset explicitly when reading files in code that must run on older versions.

Scanner implements Closeable. Close scanners over files you opened, preferably with try-with-resources. Don't close a scanner that wraps System.in: closing it closes System.in itself, and any later attempt to read the keyboard — even with a new Scanner — fails with NoSuchElementException. Create one keyboard scanner for the whole program and leave it open.

Reading Different Types

import java.util.Scanner;

public class S1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Name: ");
        String name = sc.nextLine();
        System.out.print("Age: ");
        int age = sc.nextInt();
        System.out.print("Height in metres: ");
        double height = sc.nextDouble();
        System.out.println();
        System.out.println(name + " is " + age + " years old and " + height + " m tall");
    }
}

A session in a terminal (the user's typing appears after each prompt):

Name: Asha Rao
Age: 27
Height in metres: 1.62

Asha Rao is 27 years old and 1.62 m tall
MethodReadsExample input → result
next()The next token as a StringAsha Rao → "Asha"
nextLine()The rest of the current line, without the line terminatorAsha Rao → "Asha Rao"
nextInt(), nextLong(), nextShort(), nextByte()The next token as an integer type27 → 27
nextDouble(), nextFloat()The next token as a floating-point number1.62 → 1.62
nextBoolean()true or false, ignoring caseTRUE → true
nextBigDecimal(), nextBigInteger()Exact decimal / arbitrarily large integer250.50 → 250.50
  • print (not println) keeps the cursor on the prompt line, so the user types right after the prompt.
  • nextLine() is used for the name because it can contain spaces; next() would return only Asha.
  • Each nextXxx() method blocks until enough input is available — for keyboard input, until the user presses Enter.

The nextInt / nextLine Trap

This program asks for a number and then a line of text:

import java.util.Scanner;

public class Pitfall {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Quantity: ");
        int qty = sc.nextInt();
        System.out.print("Delivery note: ");
        String note = sc.nextLine();
        System.out.println();
        System.out.println("qty=" + qty + ", note=\"" + note + "\"");
    }
}

In a terminal, the user types 3, presses Enter — and the program doesn't wait for the note at all:

Quantity: 3
Delivery note: 
qty=3, note=""

Why it happens: the input is 3\n. nextInt() reads the token 3 and stops right after it, leaving the line terminator \n unread. nextLine() then reads "the rest of the current line", which is empty, and returns "" immediately.

Two reliable fixes:

  1. Read every line with nextLine() and parse it yourself — the approach most experienced developers use for interactive input:
import java.util.Scanner;

public class Fixed {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Quantity: ");
        int qty = Integer.parseInt(sc.nextLine().strip());
        System.out.print("Delivery note: ");
        String note = sc.nextLine();
        System.out.println();
        System.out.println("qty=" + qty + ", note=\"" + note + "\"");
    }
}
Quantity: 3
Delivery note: Leave at the gate

qty=3, note="Leave at the gate"
  1. Consume the leftover line terminator with an extra sc.nextLine(); after nextInt(). This works, but it's easy to forget when code changes, and it also silently discards anything else the user typed on that line.

The rule: don't mix token methods (nextInt, next, nextDouble) and nextLine on the same scanner without thinking about where the line terminator is.

Validating Input

If the next token doesn't match the requested type, nextInt() throws InputMismatchException — and the bad token stays in the scanner. A loop that catches the exception and calls nextInt() again reads the same bad token forever. Two safe approaches: check first with a hasNextXxx() method, or read the whole line and parse it, as here:

import java.util.Scanner;

public class Valid {
    static int readInt(Scanner sc, String prompt, int min, int max) {
        while (true) {
            System.out.print(prompt);
            if (!sc.hasNextLine()) throw new IllegalStateException("no more input");
            String text = sc.nextLine().strip();
            System.out.println(text);
            try {
                int value = Integer.parseInt(text);
                if (value >= min && value <= max) return value;
                System.out.println("  please enter a number from " + min + " to " + max);
            } catch (NumberFormatException e) {
                System.out.println("  \"" + text + "\" is not a whole number");
            }
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int seats = readInt(sc, "Seats (1-6): ", 1, 6);
        System.out.println("booked " + seats + " seats");
    }
}

Output with the input lines two, 9 and 4 piped in (printf 'two\n9\n4\n' | java Valid):

Seats (1-6): two
  "two" is not a whole number
Seats (1-6): 9
  please enter a number from 1 to 6
Seats (1-6): 4
booked 4 seats
  • hasNextLine() returns false when the input has ended (Ctrl+D / end of a piped file). Without this check, nextLine() would throw NoSuchElementException; here the method reports it clearly instead of looping forever.
  • The line is echoed with System.out.println(text) only so that piped input shows up in the output; in an interactive terminal you'd remove that line, because the terminal already displays what the user types.
  • Two kinds of validation: the format ("two" isn't a number) and the range (9 is outside 1–6). Both repeat the prompt.
  • Wrapping this in a reusable readInt method keeps the rest of the program free of validation loops.

The hasNext family — hasNext(), hasNextInt(), hasNextDouble(), hasNextLine() and others — checks without consuming anything, so it's safe to call before deciding which next method to use.

Tokens, Delimiters and Parsing Strings

import java.util.*;

public class Tokens {
    public static void main(String[] args) {
        Scanner words = new Scanner("  Java   is\tfun \n to learn ");
        List<String> list = new ArrayList<>();
        while (words.hasNext()) list.add(words.next());
        System.out.println("tokens: " + list);

        Scanner mixed = new Scanner("PEN-01 12 4.50 true");
        String sku = mixed.next();
        int qty = mixed.nextInt();
        double price = mixed.nextDouble();
        boolean gift = mixed.nextBoolean();
        System.out.println(sku + " x" + qty + " @ " + price + " gift=" + gift);

        Scanner csv = new Scanner("Asha,91,Chennai\nRavi,78,Madurai\n").useDelimiter(",|\\R");
        while (csv.hasNext()) {
            String name = csv.next();
            int score = csv.nextInt();
            String city = csv.next();
            System.out.println(name + " (" + city + ") scored " + score);
        }

        System.out.println("sum via tokens(): " + new Scanner("10 20 30").tokens().mapToInt(Integer::parseInt).sum());
        try {
            new Scanner("ten").nextInt();
        } catch (InputMismatchException e) {
            System.out.println("InputMismatchException for \"ten\"");
        }
        try {
            new Scanner("").next();
        } catch (NoSuchElementException e) {
            System.out.println("NoSuchElementException on empty input");
        }
    }
}

Output (in an English locale):

tokens: [Java, is, fun, to, learn]
PEN-01 x12 @ 4.5 gift=true
Asha (Chennai) scored 91
Ravi (Madurai) scored 78
sum via tokens(): 60
InputMismatchException for "ten"
NoSuchElementException on empty input
  • Default delimiter: any run of whitespace — spaces, tabs and newlines — so extra spacing disappears and tokens can span lines.
  • Mixed types: reading tokens in the right order with the matching next methods parses a whole record from one line.
  • useDelimiter(regex) changes what separates tokens. ",|0R" means "a comma or a line break" (\R matches \n, \r\n and \r), so each comma-separated field becomes a token across both lines. This works for simple CSV, but not for quoted fields containing commas — use a CSV library for real CSV files.
  • tokens() (Java 9+) returns the remaining tokens as a Stream<String>; findAll(regex) returns all matches of a pattern.
  • Exceptions: InputMismatchException when a token doesn't fit the type; NoSuchElementException when there are no more tokens. Both are unchecked, so the compiler won't remind you to handle them.

Locale and Number Formats

nextInt, nextDouble and nextBigDecimal interpret numbers according to the scanner's locale, which defaults to the user's system locale:

import java.util.*;

public class Loc {
    public static void main(String[] args) {
        System.out.println("ROOT:   " + new Scanner("1234.5").useLocale(Locale.ROOT).nextDouble());
        System.out.println("GERMANY \"1234,5\": " + new Scanner("1234,5").useLocale(Locale.GERMANY).nextDouble());
        System.out.println("GERMANY hasNextDouble(\"1234.5\"): " + new Scanner("1234.5").useLocale(Locale.GERMANY).hasNextDouble());
        System.out.println("US \"1,234.5\": " + new Scanner("1,234.5").useLocale(Locale.US).nextDouble());
    }
}

Output:

ROOT:   1234.5
GERMANY "1234,5": 1234.5
GERMANY hasNextDouble("1234.5"): false
US "1,234.5": 1234.5

In a German locale the comma is the decimal separator and the dot is a grouping separator, so 1234,5 is valid and 1234.5 isn't. Locale-aware parsing is right for numbers a person types in their own format. For data with a fixed format — files, protocols, tests — always set useLocale(Locale.ROOT) (or Locale.US), otherwise the same program and the same input give different results on a machine with a different language setting. Integer.parseInt and Double.parseDouble are never locale-dependent, which is another argument for reading lines and parsing them yourself.

Practical Example: A Command-Driven Expense Tracker

Many console tools read commands line by line: a word that selects an action, followed by arguments. A common, robust design uses one scanner for lines and a second scanner per line to split that line into tokens — so a malformed command can never leave the main input in a strange position.

import java.math.BigDecimal;
import java.util.*;

public class Expenses {
    record Expense(String category, BigDecimal amount, String note) { }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in).useLocale(Locale.ROOT);
        List<Expense> expenses = new ArrayList<>();
        while (true) {
            System.out.print("> ");
            if (!sc.hasNextLine()) break;
            String line = sc.nextLine().strip();
            System.out.println(line);
            if (line.isEmpty()) continue;
            Scanner cmd = new Scanner(line).useLocale(Locale.ROOT);
            String action = cmd.next().toLowerCase();
            switch (action) {
                case "add" -> {
                    String category = cmd.hasNext() ? cmd.next() : null;
                    if (category == null || !cmd.hasNextBigDecimal()) {
                        System.out.println("  usage: add CATEGORY AMOUNT [NOTE]");
                        continue;
                    }
                    BigDecimal amount = cmd.nextBigDecimal();
                    String note = cmd.hasNextLine() ? cmd.nextLine().strip() : "";
                    expenses.add(new Expense(category, amount, note));
                    System.out.println("  added " + amount + " to " + category);
                }
                case "summary" -> {
                    Map<String, BigDecimal> byCat = new TreeMap<>();
                    for (Expense e : expenses) byCat.merge(e.category(), e.amount(), BigDecimal::add);
                    byCat.forEach((c, total) -> System.out.printf("  %-10s %10s%n", c, total));
                    System.out.printf("  %-10s %10s%n", "TOTAL",
                        expenses.stream().map(Expense::amount).reduce(BigDecimal.ZERO, BigDecimal::add));
                }
                case "quit" -> {
                    System.out.println("  bye");
                    return;
                }
                default -> System.out.println("  unknown command: " + action);
            }
        }
        System.out.println("(end of input)");
    }
}

Output with these commands piped in: add food 250.50 lunch with team, add travel 1200, add food 99.5, add books, list, summary, quit:

> add food 250.50 lunch with team
  added 250.50 to food
> add travel 1200
  added 1200 to travel
> add food 99.5
  added 99.5 to food
> add books
  usage: add CATEGORY AMOUNT [NOTE]
> list
  unknown command: list
> summary
  food           350.00
  travel           1200
  TOTAL         1550.00
> quit
  bye

Step by step:

  1. The outer scanner only reads lines. hasNextLine() ends the loop cleanly when input runs out; quit ends it with return. (The println(line) echo is there only to make piped input visible.)
  2. A new scanner per line parses the command. The first token selects the action, using a switch on strings.
  3. add validates before reading. If the category is missing or the next token isn't a valid decimal (hasNextBigDecimal()), it prints usage and continues to the next prompt. Because the line has its own scanner, nothing is left over to confuse the next command.
  4. The note is the rest of the line: after the amount, nextLine() on the line scanner returns everything remaining (" lunch with team"), stripped of the leading space. This is the token-then-line mix working for you, on a scanner that contains only one line.
  5. Money uses BigDecimal, so 250.50 + 99.5 is exactly 350.00 (the scale of the result is the larger of the two). Locale.ROOT guarantees the dot is the decimal separator regardless of the system language.
  6. Map.merge totals by category in a TreeMap (sorted output), and reduce computes the grand total.

The same structure — read a line, split it into a command and arguments, validate, dispatch — is how shells, database consoles and admin tools are built.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Scanner Class and get answers drawn from it.

Signed-in readers only.