Explain enhanced ‘for-loop’ in Java.
Answered
Explain enhanced ‘for-loop’ in Java. How is it different from regular loop?
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); }