Quantcast
Viewing all articles
Browse latest Browse all 30

Answer by MRocklin for In detail, how does the 'for each' loop work in Java?

Here is an answer which does not assume knowledge of Java Iterators. It is less precise, but it is useful for education.

While programming we often write code that looks like the following:

char[] grades = ....for(int i = 0; i < grades.length; i++) {   // for i goes from 0 to grades.length    System.out.print(grades[i]);           // Print grades[i]}

The foreach syntax allows this common pattern to be written in a more natural and less syntactically noisy way.

for(char grade : grades) {   // foreach grade in grades    System.out.print(grade); // print that grade}

Additionally this syntax is valid for objects such as Lists or Sets which do not support array indexing, but which do implement the Java Iterable interface.


Viewing all articles
Browse latest Browse all 30

Trending Articles