Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)

Can anyone help me understand the below code, which contains hasNext() and .next() method which I was not able to understand.

import java.util.*;  // imported whole java.util package.

class Main {

  public static void main(String[] args) {

    ArrayList<String> cars = new ArrayList<String>();  // created ArrayList which name is cars.

    cars.add("Volvo");

    cars.add("Mercedes"); 

    cars.add("BMW");

    Iterator<String> x = cars.iterator();

    while(x.hasNext()) {

      System.out.print(x.next() + " ");  // It prints Volvo Mercedes BMW

    }

  }

}

Any help would be appreciated.

1 Answer

0 votes
by (26.7k points)

Basically, the .hasNext() method helps us to check whether the array list contains that particular element or not, if it is there then, it will return true or else false. Whereas, .next() method helps you to return the next element from the iteration.

I hope this will help.

Want to become a Java Expert? Join Java Certification now!!

Want to know more about Java? Watch this video on Java Course | Java Tutorial for Beginners:

Related questions

0 votes
1 answer
asked Mar 6, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Sep 23, 2019 in Java by Ritik (3.5k points)

Browse Categories

...