Javatpoint Logo
Javatpoint Logo

Java Scanner hasNext() Method

The hasNext() is a method of Java Scanner class which returns true if this scanner has another token in its input. There are three different types of Java Scanner hasNext() method which can be differentiated depending on its parameter. These are:

  1. Java Scanner hasNext () Method
  2. Java Scanner hasNext (String pattern) Method
  3. Java Scanner hasNext(Pattern pattern) Method

1.Java Scanner hasNext () Method:

It is a Scanner class method which returns true if this scanner has another token in its input. This method may block while waiting for input to scan.

2.Java Scanner hasNext (String pattern) Method:

It is a Scanner class method which returns true if the next token matches the pattern constructed from the specified string.

3.Java Scanner hasNext (Pattern pattern) Method:

It is a Scanner class method which returns true if the next complete token matches the specified pattern.

Syntax

Following are the declarations of hasNext() method:

Parameter

Data Type Parameter Description Required/Optional
String pattern It is a string specifying the pattern to scan. Required
Pattern pattern It is the pattern to scan for specified string. Required

Returns

Method Returns
hasNext() This method returns true if and only if this scanner has another token.
hasNext(String pattern) This method returns true if and only if this scanner has another token matching the specified pattern.
hasNext(Pattern pattern) This method returns true if and only if this scanner has another token matching the specified pattern.

Exceptions

IllegalStateException- This method throws exception if the innvocation is done after the scanner has been closed.

Compatibility Version

Java 1.5 and above

Example 1

Output:

Delimiter:\p{javaWhitespace}+
Hello
World!

Example 2

Output:

Result: true
String: Hello, This is JavaTpoint.
Final Result: false

Example 3

Output:

Pattern found

Example 4

Output:

Result: true
Result: false
Rest of String: JavaTpoint.com 15 + 15 = 18.0

Example 5

Output:

Pawan
Suresh

Next TopicJava Scanner Class



Help Others, Please Share

facebook twitter pinterest