-2

Usually I have seen for loops such as:

for(int i; i < 10; i++) {
   // do something
}

What type of for loop is this, and how does it work in Java?

Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            for (RunnableProducer p : runnableProducers) p.shutdown();
Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66
  • 2
    This is just code. Please read [ask] and [edit] your question. Include the actual question in the main body and not the title. – The Grand J Sep 21 '20 at 03:03
  • This is kind a foreach loop which itterate over an array elements. Read about foreach loop – Basit Sep 21 '20 at 06:06
  • Some call it an "enhanced for loop", at [Oracle's Java Tutorial for "The for Statement"](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html) the mention "enhanced for statement" – Scratte Sep 21 '20 at 14:31

2 Answers2

0

It is called for-each (or enhanced for loop) loop. You can learn more about it here.

Syntax:

for(data_type item : collections) {
    ...
}

How it works:

For each iteration, the loop

  1. iterates through each item given in collection or arrays(collection)
  2. stores each in a variable (item)
  3. and executes the body of the loop.

(read more here)

ganjaam
  • 1,030
  • 3
  • 17
  • 29
0

This is called a for-each loop, a.k.a. "enhanced for loop" in Java. It is, at the basic level, a syntactic sugar for the for loops which iterate over Iterable collections. This construct gets rid of the clutter which is present in for loops with Iterables, and therefore, it minimizes possible errors in the code.

As Java 8 doc instructs:

for (Iterator<TimerTask> i = c.iterator(); i.hasNext(); )
    i.next().cancel();
}

can be rewritten as:

for (TimerTask t : c)
        t.cancel();
}

It's cleaner and it's prone to less mistakes and errors.

Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66