Java Scanner hasNext()

In this guide, you will learn about the Scanner hasNext() method in Java programming and how to use it with an example.

1. Scanner hasNext() Method Overview


The hasNext() method of the Scanner class in Java checks if there is another token available in the input of this scanner. This method is particularly useful in loops to check if there's more data to process.


public boolean hasNext()


This method does not take any parameters.

Key Points:

- The method returns true if there's another token available, otherwise, it returns false.

- This method is blocking, which means if you call it, it might wait indefinitely until there's more input (like if the input source is the console).

- It does not advance the scanner past any input.

2. Scanner hasNext() Method Example

import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(;

        System.out.println("Enter some words, type 'exit' to quit:");
        while(scanner.hasNext()) {
            String word =;
            if("exit".equalsIgnoreCase(word)) {
            System.out.println("You entered: " + word);


Enter some words, type 'exit' to quit:
You entered: hello
You entered: world


In this example, the program prompts the user to enter words. It uses the hasNext() method to determine if there is another word available in the input. The loop keeps reading words until the user enters 'exit', which will break out of the loop.