Java Scanner next() Method

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

Definition

In Java, sc.next() finds and returns the next complete token from the scanner as a String. With the default whitespace delimiter, a token is one word separated by spaces, tabs, or line breaks.

Unlike nextLine(), next() skips any leading delimiter characters, stops right before the next delimiter, and throws NoSuchElementException when no more tokens exist.

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.next(...).

Syntax

Call next() with no arguments for any token, or pass a regex String or Pattern that the full token must match.

Java
Scanner sc = new Scanner("Ada 42");
String first = sc.next();                 // "Ada"
String num = sc.next("\\d+");             // "42"
Pattern code = Pattern.compile("[A-Z]+"); // compile once for reuse
CallWhat it does
sc.next()Reads the next token delimited by the current delimiter.
sc.next("[A-Z]+")Reads the next token only if the whole token matches the regex.
sc.next(pattern)Same check using a precompiled Pattern object.
sc.hasNext()Check before calling next() to avoid NoSuchElementException.

With next(pattern), the pattern must match the entire delimited token, not just a part inside it. To search inside a line ignoring delimiters, use findInLine().

Library declarations
Java
// java.util.Scanner
public String next()
public String next(Pattern pattern)
public String next(String pattern)

Parameters

ParameterDescription
pattern (optional)A regex String or compiled Pattern that the entire next token must match.

Return Value

Return ValueDescription
StringThe next complete token (never containing delimiter characters unless the delimiter pattern is empty).
Throws NoSuchElementExceptionIf no more tokens remain, or if the next token fails to match the given pattern.
Throws IllegalStateExceptionIf the scanner has already been closed.

Compare with Similar Methods

Reading tokens versus lines and lookahead:

MethodHow it differs
nextLine()Reads spaces too, up to the next line break.
hasNext()Tests whether a matching token is ready without consuming it.
findInLine(p)Matches anywhere on the current line, ignoring delimiters.
useDelimiter(p)Changes what counts as a separator between tokens.

Java Examples

Example 1 — Read Space-Separated Words Until Input Ends

Split a short sentence into words using default whitespace delimiters, then trigger NoSuchElementException past the end.

Java
import java.util.NoSuchElementException;
import java.util.Scanner;

public class ScannerNextWords {
    public static void main(String[] args) {
        String text = "Java   Scanner\ttokens";
        try (Scanner sc = new Scanner(text)) {
            while (sc.hasNext()) {
                System.out.println("Word: " + sc.next());
            }
            try {
                sc.next();
            } catch (NoSuchElementException e) {
                System.out.println("Exhausted: " + e.getClass().getSimpleName());
            }
        }
    }
}

How It Works

  1. Whitespace collapses automatically. Three spaces and a tab between words count as one delimiter under the default pattern, so next() returns three clean words.
  2. Guarded loop finishes cleanly. hasNext() turns false after "tokens", preventing an unexpected crash during normal reading.
  3. Past end of input. Calling sc.next() once no tokens remain raises NoSuchElementException, caught and named via getSimpleName().

Example 2 — Validate Token Format with next(Pattern) and next(String)

Require an order code like AB-104, then see what happens when the next token fails the regex.

Java
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.regex.Pattern;

public class ScannerNextPattern {
    public static void main(String[] args) {
        Pattern orderCode = Pattern.compile("[A-Z]{2}-\\d{3}");
        try (Scanner sc = new Scanner("AB-104 42 oops")) {
            String code = sc.next(orderCode);
            String qty = sc.next("\\d+");
            System.out.println("Code: " + code + ", Qty: " + qty);
            try {
                sc.next("\\d+");
            } catch (NoSuchElementException e) {
                System.out.println("Rejected token: " + sc.next());
            }
        }
    }
}

How It Works

  1. Full-token regex match. orderCode checks two uppercase letters, a hyphen, and three digits across the whole token "AB-104".
  2. String pattern overload. Passing "\\d+" verifies that the second token consists only of digits before returning "42".
  3. Failed match leaves token behind. When "oops" fails "\\d+", NoSuchElementException fires without advancing, so sc.next() in catch still reads "oops".

Example 3 — Read a Single-Word Handle from the Keyboard (System.in)

Ask for a single-word handle and a tag using System.in. Keep one scanner open for System.in rather than closing it early.

Java
import java.util.Scanner;

public class ScannerNextKeyboard {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a single-word username:");
        String user = sc.next();
        System.out.println("Enter your team code:");
        String team = sc.next();
        System.out.println("Welcome @" + user + " (" + team + ")");
    }
}

How It Works

  1. Standard input source. Wrapping System.in pauses at each next() call until you type a word and press Enter.
  2. Spaces split tokens. If someone typed two words on the first line, the second word would immediately satisfy the second sc.next() call.
  3. Leave System.in open. Avoiding close() here keeps System.in usable for any other code running later in the JVM.

Frequently Asked Questions

It returns the next complete token as a String, stopping right before the next delimiter.
next() stops at whitespace (or your custom delimiter) and reads one token, whereas nextLine() reads spaces too until the next line separator.
Either there are no more tokens left in the input, or you used next(pattern) and the next token did not match the pattern.
No. The pattern must match the entire next token from start to end. Use findInLine() if you want to search for a substring inside a line.
Yes, under the default whitespace delimiter. Calling next() skips any leading spaces, tabs, or newlines before the next token.

Next: nextBigDecimal()

Read the next token as an exact BigDecimal.

nextBigDecimal() 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