java.util.Scanner hasNext()

Description :

This java tutorial shows how to use the hasNext() method of Scanner class of java.util package. This method returns a boolean data type which serves as a flag if there are still tokens to iterate over.

Method Syntax :

public boolean hasNext()

Parameter Input :

 

DataType Parameter Description
N/A N/A N/A

 

Method Returns :

This method returns true if the Scanner still has tokens to process

Compatibility Version :

Requires Java 1.5 and up

Exception :

IllegalStateException

The IllegalStateException will be thrown if and only if the scanner is already closed (invoking close() method) and still we invoke the hasNext() method.

Discussion :

The Scanner hasNext() method is usually used as a flag in iterating through the tokens of this scanner object. I could never remember already how many times i have used this handy method especially in dealing with codes that do complex string manipulation.

Java Code Example :

This java example source code demonstrates the use of hasNext() method of Scanner class. Basically this code just prints the tokens generated by the Scanner object.

package com.teknoscope.java.tutorial.scanner;

import java.util.Scanner;

/*
 * This is an example source code that prints the delimiter
 * and print the string tokens
 */

public class ScannerHasNextDemo {

	public static void main(String[] args) {

		// Initialize Scanner object
		Scanner scan = new Scanner("This an example string");
		// Printing the delimiter used
		System.out.println("Delimiter:" + scan.delimiter());
		// Printing the tokenized Strings
		while (scan.hasNext()) {
			System.out.println(scan.next());
		}
		// closing the scanner stream
		scan.close();

	}

}

Sample Output :

Running the hasNext() method example source code of Scanner class will give you the following output

java scanner hasnext() method example

java scanner hasnext() method example

Exception Scenario :

Exception in thread "main" java.lang.IllegalStateException: Scanner closed
	at java.util.Scanner.ensureOpen(Unknown Source)
	at java.util.Scanner.hasNext(Unknown Source)

Similar Method :

  • N/A

Suggested Reading List :

References :