[java] What is the syntax of the enhanced for loop in Java?

I have been asked to use the enhanced for loop in my coding.

I have only been taught how to use traditional for loops, and as such don't know about the differences between it and the enhanced for loop.

How does an enhanced for loop differ from a traditional for loop in Java?

Are there any intricacies that I should look out for which tutorials tend not to mention?

This question is related to java foreach

The answer is


An enhanced for loop is just limiting the number of parameters inside the parenthesis.

for (int i = 0; i < myArray.length; i++) {
    System.out.println(myArray[i]);
}

Can be written as:

for (int myValue : myArray) {
    System.out.println(myValue);
}

  1. Enhanced For Loop (Java)
for (Object obj : list);
  1. Enhanced For Each in arraylist (Java)
ArrayList<Integer> list = new ArrayList<Integer>(); 
list.forEach((n) -> System.out.println(n));