Explain enhanced ‘for-loop’ in Java.

Answered

Explain enhanced ‘for-loop’ in Java. How is it different from regular loop?

Ninja Asked on 17th September 2018 in Java.
Add Comment
1 Answer(s)
Best answer

The enhanced for-loop is a popular feature introduced with the Java SE platform in version 5.0. Its simple structure allows one to simplify code by presenting for-loops that visit each element of an array/collection without explicitly expressing how one goes from element to element.

For example, the standard for loop steps through an array as

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

The so-called enhanced for loop is a simpler way to do this same thing hiding the index, also referred as for-each loop.

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

Ninja Answered on 17th September 2018.
Add Comment