Core Java

Scanner hasNext() Java Example

This article will feature a comprehensive Example on Java Scanner hasNext method. We will also understand the hasNext method of Iterator interface with suitable example.

1. Introduction

In Java, Scanner is a simple text reader which can parse primitive types and strings using regular expressions. It has been added to JDK 1.5. It breaks its input into tokens using a delimiter pattern which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

2. Java.util.Scanner.hasNext()

java.util.Scanner class provides a method hasNext to check if an input token is present and it returns true if this scanner has another token in its input. This method may block while waiting for input to scan and the scanner does not advance past any input.

Below code demonstrates a simple example with Scanner hasNext method.

public class ScannerHasNextExample {

	public static void main(String[] args) {

		Scanner sc = new Scanner(; // Scanner is instantiated with
		String input = null;

		while(sc.hasNext() && !(input ="exit")) {

		sc.close(); // Scanner is closed

In the above example, the scanner is instantiated to read user input. Inside the while loop, hasNext() method blocks the main thread until an input token from console is available and prints the token. The program prints the input tokens until the string ‘exit’ is entered. The above example prints an output like below after execution.

hasNext Java - Output of  ScannerHasNextExample
Fig 1. Output of ScannerHasNextExample

Scanner also allows us to define custom delimiter using the useDelimiter method. When a custom delimiter is defined for Scanner, it splits input tokens based on the delimiter defined and this is explained as part of the below example. ScannerHasNextWithDelimiterExample

public class ScannerHasNextWithDelimiterExample {

	public static void main(String[] args) {

		Scanner sc = new Scanner(" how .");

		sc.useDelimiter("\\."); // Custom delimiter dot is defined

		while(sc.hasNext()) {
			System.out.println(; // Printing the input token scanned

		sc.close(); // Scanner is closed

In the above example, dot is defined as the delimiter for the Scanner which is instantiated with a String source. It splits the input using the defined delimiter dot. When it is looped over hasNext method to check for input, the split input tokens are printed in the console like below

hasNext Java - Output of  ScannerHasNextWithDelimiterExample
Fig 2. Output of ScannerHasNextWithDelimiterExample

3. Java.util.Iterator.hasNext()

Java provides Iterator interface to iterate over elements of a collection. java.util.Iterator should be preferred over java.util.Enumeration for iteration in the Java Collections Framework. It differs from enumeration in two ways like stated below

  • Iterator allows the caller to remove elements from the underlying collection during the iteration using remove() method.
  • Method names in Iterator have been improved.

Iterator interface provides hasNext method which returns true if the backing collection has more elements.

Below is an example to understand how hasNext method is used for iterating over a collection. JavaIteratorHasNextExample

public class JavaIteratorHasNextExample {

	public static void main(String[] args) {
		List  li = new ArrayList(); // ArrayList is instantiated 


		Iterator itr = li.listIterator();  // List iterator instance is obtained 
		System.out.println("The final list for integer value is given as: ");  


In the above example, ListIterator which implements the iterator interface is obtained for an ArrayList of Integers. Inside the while loop, the iterator is checked for an element being present using its hasNext method and the element is printed.

The above code when executed produces an output like below.

hasNext Java - Output of  JavaIteratorHasNextExample
Fig 3. Output of JavaIteratorHasNextExample

4. Summary

In the article, we have understood the characteristics of Scanner’s hasNext method and how to use it to check for input tokens with examples. Also, we have understood what an iterator interface is and how its hasNext method can be used for iterating over collections

6. Download the Source Code

This source contains the example code snippets used in this article to illustrate the Scanner hasNext and Iterator hasNext methods.

You can download the full source code of this example here: Scanner hasNext() Java Example

Last updated on Jul. 28th, 2021

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Aarish Ramesh

He is a polyglot developer with great experience designing, building highly scalable and robust software. He holds a Master’s degree in Software Systems from BITS, Pilani, India and Bachelor’s degree in Electronics and Communication from SSN College of Engineering, Chennai, India . He has been associated earlier with engineering roles in e-commerce and productivity software companies like Cleartrip and Zoho. During his professional career and studies, he has been majorly involved in software projects involving Java, Big data technologies and ecosystem
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button