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 :


DataType Parameter Description


Method Returns :

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

Compatibility Version :

Requires Java 1.5 and up

Exception :


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


– 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.


import java.util.Scanner;

 * This is an example source code that reads input from console
 * and tokenize using Scanner object
 * Prints the tokens using next() method

public class ScannerNextDemo {

	public static void main(String[] args) {

		System.out.print("Enter your full name:");
		// Initialize Scanner object
		// read the value from the console
		Scanner scan = new Scanner(;
		// read the first token
		String firstName =;
		// read the second token
		String lastName =;
		// Printing the token values of read by Scanner object
		System.out.println("First Name is "+firstName);
		System.out.println("Last Name is "+lastName);

		// closing the scanner stream



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 :

Exception in thread "main" java.lang.IllegalStateException: Scanner closed
	at java.util.Scanner.ensureOpen(Unknown Source)
	at Source)

Exception in thread "main" java.util.NoSuchElementException
	at java.util.Scanner.throwFor(Unknown Source)
	at Source)

Similar Method :

  • N/A

Suggested Reading List :

References :