What is the difference between hasNext() and next() and where it is used? Is it used in Selenium WebDriver or Selenium IDE.

  • 1
    Voting for closing: This question is better placed in StackOverflow Jun 11, 2019 at 11:59
  • 1
    This is an extremely basic coding question that will be downvoted to oblivion in StackOverflow. hasNext() checks whether the collection has any more elements, next() moves to the next elements in a collection. Neither have any relationship to Selenium. They are used in the programming language that is working with Selenium.
    – Kate Paulk
    Jun 11, 2019 at 13:47

2 Answers 2


I think Kannathasan has explained the difference perfectly, but I'd like to add some context:

Making the assumption that you're using Java, they're part of the Iterator interface as described here: https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html

This interface is a part of Java. While it has nothing to do with Selenium-Webdriver, parts of Selenium-Webdriver may implement it.

From the documentation:


boolean hasNext()

Returns true if the iteration has more elements. (In other words, returns true if next() would return an element rather than throwing an exception.)

    true if the iteration has more elements 


E next()

Returns the next element in the iteration.

    the next element in the iteration
    NoSuchElementException - if the iteration has no more elements

I can't think of a place in Selenium-Webdriver where I've used an iterator directly, but it's implemented in a few places where you could use it if you really wanted to.

If you have an ArrayList for example, you can access and use the Iterator instead of using a for loop. There may be times where this is advantageous, but I can't think of any immediate examples.

Take this simple use with an ArrayList

 List <String> strings = new ArrayList <String>();

 strings.add("Example 1");
 strings.add("Example 2");

 Iterator<String> iterator = strings.iterator();

 while (iterator.hasNext()) {

While there are still items in the list to go through, it will print them out. As there are 2 items in the list, it will run through 2 iterations and print out both strings that were added.


hasNext is used to iterate the windows in selenium webdriver here is the difference

hasNext() will return true if iteration has more values

next() will return the next element in iteration

Not the answer you're looking for? Browse other questions tagged or ask your own question.