Enhanced For Loop in Java
In the previous post, we learnt For Loop in Java. In this post we will see Enhanced For Loop. The Enhanced For Loop is designed for iteration through Collections and arrays. This enhanced for loop makes our loops more compact and easy to read.
Syntax:
//temporary iterator variable is declared in the loop for(dataType iteratorVariable : IterableObject){ //the individual element is held in the iterator variable //to access the value, just use iteratorVariable }
Let’s see following example with array. Check this link to learn Arrays in Java.
Sample Program:
package ClassThreeControlFlowStatements; public class EnhancedForLoop { public static void main(String[] args) { int numbers[] = {1,2,3,4,5,6,7,8,9,10}; //for(dataType iteratorVariable : IterableObject){ for (int count : numbers){ System.out.println("Count is : "+count); } } }
Must Read: Java Tutorial