Java Scanner next() Method

The next() is a method of Java Scanner class which finds and returns the next complete token from the scanner which is in using. There are three different types of Java Scanner next() method which can be differentiated depending on its parameter. These are:

  • Java Scanner next() Method
  • Java Scanner next(String pattern) Method
  • Java Scanner next(Pattern pattern) Method

1. Java Scanner next() Method

It is a Scanner class method used to get the next complete token from the scanner which is in using. A complete token is preceded and followed by input that matches the delimiter pattern.

2. Java Scanner next(String pattern) Method

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

3. Java Scanner next(Pattern pattern) Method

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

Syntax

Following are the declarations of next() method:

Parameter

DataTypeParameterDescriptionRequired/Optional
StringpatternIt is a string specifying the pattern to scan.Required
PatternpatternIt is the pattern to scan for specified string.Required

Returns

The next() method returns the next complete tokens.

Exceptions

NoSuchElementException- It will thrown this Exception if no more tokens are found.

IllegalStateException- It will thrown this Exception if the innvocation is done after Scanner is closed.

Compatibility Version

Java 1.5 and above

Example 1

Output:

Enter full name: Hritik Roshan
First Name is: Hritik
Last Name is: Roshan

Example 2

Output:

hasNextLine
public
boolean
hasNextLine()
IllegalStateException

Example 3

Output:

Token Value1 Facebook.com
Token value2: JavaTpoint.com

Example 4

Output:

tokenized Strings: 22
tokenized Strings: 313
tokenized Strings: 45
tokenized Strings: 87

Example 5

Output:

JavaTpoint
Hello