java.util.Scanner hasNext(String pattern)

Description :

This java tutorial shows how to use the hasNext(String pattern) method of Scanner class of java.util package. This method returns a boolean data type which corresponds if there is an available token given a String pattern specified as method argument.

Method Syntax :

public boolean hasNext(String pattern)

Parameter Input :


DataType Parameter Description
String pattern A string pattern that Scanner object used in tokenizing


Method Returns :

This method simply returns boolean which corresponds the result of pattern matching. Returns true if the Scanner has token that matches the String pattern specified as method argument.

Compatibility Version :

Requires Java 1.5 and up

Exception :


Discussion :

The Scanner hasNext(String pattern) method is used a flag if we can iterate further on the String tokens. This is a shortcut of calling the hasNext(Pattern.compile(String pattern)) which yields the same result.

Java Code Example :

This java example source code demonstrates the use of hasNext(String pattern) method of Scanner class. Basically we just check if the pattern satisfies the next token.


import java.util.Scanner;

 * This is an example source code that shows the usage of hasNext(String pattern)
 * method of Scanner class
 * Java Tutorial

public class ScannerHasNextStringPatternDemo {

	public static void main(String[] args) {

		// Initialize Scanner object
		Scanner scan = new Scanner("Names:Anna;William;Kingsly");
		// Initialize the String pattern
		String pattern = "Names:.*";
		// check if pattern satisfies the String content
			System.out.println("Pattern found");
			System.out.println("Pattern not found");
		// closing the scanner stream



Sample Output :

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

java scanner hasnext(pattern) method example

java scanner hasnext(pattern) method example

Exception Scenario :


Similar Method :

  • N/A

Suggested Reading List :

References :