java.util.Scanner hasNext(Pattern pattern)

Description :

This java tutorial shows how to use the hasNext(Pattern 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 object specified as method argument.

Method Syntax :

public boolean hasNext(Pattern pattern)

Parameter Input :

[table]
DataType|Parameter|Description
Pattern|pattern|An object pattern that Scanner object used in tokenizing
[/table]

Method Returns :

This method simply returns boolean which corresponds the result of pattern matching. Returns true if the Scanner has token that matches the object Pattern specified as method argument, otherwise it’s false.

Compatibility Version :

Requires Java 1.5 and up

Exception :

IllegalStateException

The IllegalStateException will be thrown by hasNext(Pattern pattern) method of Scanner class if the method invocation is done after the scanner is closed.

Discussion :

The Scanner hasNext(Pattern pattern) method is used a flag if we can iterate further on the String tokens. This is a long version of calling the method hasNext(String pattern). Looking at the java api source code, this is the same method as the latter. However the only difference is that instead of String pattern, the method argument is Pattern object.

Java Code Example :

This java example source code demonstrates the use of hasNext(Pattern pattern) method of Scanner class. Basically the code prints only those tokens that consists of alphabet on its character elements.

Sample Output :

Running the hasNext(Patttern 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 :