← BYTES
Java·Starter·Ref: 9.1.20

What is the purpose of a `for-each` loop (`for (Type item : collection)`) compared to a traditional indexed for loop?

Have a question about this video? Mention reference 9.1.20 when you contact us.

a.It iterates over every element of an array or Iterable without needing to manually manage an index variable
b.It only works with arrays, never collections
c.It runs in reverse order automatically
d.It is slower in every case than an indexed loop
The for-each (enhanced for) loop is syntactic sugar over using an Iterator internally -- it reads more cleanly for simple 'do something with every element' cases, at the cost of not giving you direct access to the index or the ability to easily remove elements mid-iteration.

Find this on YouTube & Instagram

Every BYTES video is tagged with its reference number and topic — search any of these on YouTube or Instagram to find this one:

#BYTES#BYTES9120#Java