Java Iterator hasNext() Method Tutorial

In this section, we will learn what the Iterator hasNext() method is and how to use it in Java.

What is Iterator hasNext() Method in Java?

The Java Iterator hasNext() method is used to check if there’s still another element in an Iterator object or not.

Iterator hasNext() Method Syntax:

boolean hasNext()

Iterator hasNext() Method Parameters

The method does not take an argument.

Iterator hasNext() Method Return Value

The return value of this method is of type Boolean.

If there is another value still in the target iterator object, the return value of this method becomes true otherwise, if there’s no element, the return value becomes false.

Iterator hasNext() Method Exception:

The method does not throw an exception.

Example: using Iterator hasNext() Method in Java

import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class Main {

    public static void main(String[] args){
        
        List<String> list = new ArrayList<>();
        list.add("Omid");
        list.add("Jack");
        list.add("Ellen");
        list.add("John");

        Iterator<String> iterate = list.iterator();

        while(iterate.hasNext()){
         System.out.println(iterate.next());
        }
    }
}

Output:

Omid

Jack

Ellen

John
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies