In Java, sc.hasNext() looks ahead and returns true if the scanner has at least one more token waiting, without advancing past any input.
The pattern overloads hasNext(String) and hasNext(Pattern) return true only when the entire next delimited token matches the given regular expression.
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.hasNext(...).
Syntax
Use hasNext() in a while condition before calling next() so your loop stops cleanly without throwing NoSuchElementException.
Java
Scanner sc = new Scanner("red green");
while (sc.hasNext()) {
if (sc.hasNext("r.*")) { /* starts with r */ }
System.out.println(sc.next());
}
Call
What it does
sc.hasNext()
Returns true if any token remains; does not consume input.
sc.hasNext("#\\w+")
Returns true if the full next token matches the regex.
sc.hasNext(pattern)
Same full-token check using a precompiled Pattern.
Calling hasNext() twice in a row inspects the exact same token both times. On System.in, hasNext() blocks until you type characters and press Enter (or signal end of stream).
Library declarations
Java
// java.util.Scanner
public boolean hasNext()
public boolean hasNext(Pattern pattern)
public boolean hasNext(String pattern)
Parameters
Parameter
Description
pattern (optional)
Regex String or compiled Pattern that the whole next token must match.
Return Value
Return Value
Description
boolean
true if another matching token is available; false at end of input or mismatch.
Searches inside the current line ignoring delimiters.
Java Examples
Example 1 — Peek Twice Without Consuming Any Token
Verify that hasNext() never removes tokens and returns false once the last word is read.
Java
import java.util.Scanner;
public class ScannerHasNextPeek {
public static void main(String[] args) {
try (Scanner sc = new Scanner("alpha beta")) {
System.out.println("First peek: " + sc.hasNext());
System.out.println("Second peek: " + sc.hasNext());
while (sc.hasNext()) {
System.out.println("Read: " + sc.next());
}
System.out.println("At EOF: " + sc.hasNext());
}
}
}
Output
First peek: true
Second peek: true
Read: alpha
Read: beta
At EOF: false
How It Works
Lookahead stays stationary. Both peeks before the loop print true because checking leaves "alpha" unread.
Consume inside the loop. Only sc.next() advances past "alpha" and then "beta".
False at stream end. After reading the last word, hasNext() returns false cleanly without raising an exception.
Example 2 — Tag Tokens with hasNext(String) and hasNext(Pattern)
Check each token against a hashtag regex before reading so hashtags get labeled differently from plain words.
Java
import java.util.Scanner;
import java.util.regex.Pattern;
public class ScannerHasNextPattern {
public static void main(String[] args) {
Pattern tag = Pattern.compile("#[a-z]+");
String post = "learn #java and #scanner today";
try (Scanner sc = new Scanner(post)) {
while (sc.hasNext()) {
if (sc.hasNext(tag)) {
System.out.println("Tag: " + sc.next());
} else {
System.out.println("Word: " + sc.next());
}
}
}
}
}
Output
Word: learn
Tag: #java
Word: and
Tag: #scanner
Word: today
How It Works
Outer check keeps loop moving.sc.hasNext() ensures the loop inspects every token even when hasNext(tag) is false.
Regex tests the whole token. Only "#java" and "#scanner" match #[a-z]+ from start to end.
Both branches consume once. Whichever branch matches calls sc.next() once so the cursor always advances.
Example 3 — Stop a System.in Word Loop When the User Types "quit"
Read words from System.in until the user types quit, using !sc.hasNext("quit") as a lookahead guard.
Java
import java.util.Scanner;
public class ScannerHasNextQuit {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter item words (type quit to finish):");
int count = 0;
while (sc.hasNext() && !sc.hasNext("quit")) {
String item = sc.next();
count++;
System.out.println("Added #" + count + ": " + item);
}
if (sc.hasNext("quit")) {
sc.next();
}
System.out.println("Total items: " + count);
}
}
Sample run
Sample run (the user types the lines shown after the > marker). Run with java ScannerHasNextQuit.
Enter item words (type quit to finish):
> milk
Added #1: milk
> bread
Added #2: bread
> quit
Total items: 2
How It Works
Short-circuit condition. Checking sc.hasNext() before !sc.hasNext("quit") avoids inspecting a nonexistent token at EOF.
Sentinel stays outside count. When quit arrives, !sc.hasNext("quit") becomes false and stops the loop before adding it.
Consume sentinel cleanly. Calling sc.next() after the loop clears "quit" from the keyboard buffer before printing the summary.
Frequently Asked Questions
No. It only peeks ahead to check if a token is available; you still need next() to read it.
Standard input from a keyboard has no end until you send EOF (Ctrl+D on macOS/Linux or Ctrl+Z then Enter on Windows). Use a sentinel word like !sc.hasNext("quit") to stop interactively.
hasNext() checks for another non-delimiter token (ignoring trailing spaces or empty lines), whereas hasNextLine() returns true if any characters or line break remain.
No. It matches only if the entire next token conforms to the regex.
Scanner throws IllegalStateException because the scanner is closed.