java.util.Scanner next()

Description :

This java tutorial shows how to use the next() method of Scanner class of java.util package. This method returns a String object which is a complete token of the Scanner object.

Method Syntax :

public String next()

Parameter Input :

[table]
DataType|Parameter|Description
N/A|N/A|N/A
[/table]

Method Returns :

This method simply returns the next token of the Scanner object.

Compatibility Version :

Requires Java 1.5 and up

Exception :

NoSuchElementException

– The NoSuchElementException is thrown if and only if there is no available token

IllegalStateException

– This exception is thrown if the scanner is already closed before invoking the next() method.

Discussion :

The method next() gets the next token on the Scanner buffer matching the pattern used as delimiter on the scanner object. This method is used to iterate through the Scanner tokens while returning the value of the current token.

Java Code Example :

This java example source code demonstrates the use of next() method of Scanner class. Basically this code reads a full name from the input console and we have used the scanner object to store the information. We then tokenize the String input and then get the String tokens by invoking the next() method of this Scanner object.

Sample Output :

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

java scanner next() method example

java scanner next() method example

Exception Scenario :

Similar Method :

  • N/A

Suggested Reading List :

References :