Enhanced For Loop

Iterating over an array is a very common task. The Java 2 Platform , Standard Edition(J2SE) version 5.0 has added an enhanced for loop to make array iteration easier.
Syntax

for (type itr-var : collection)

{

Statement block;

}

// Use a for-each style for loop

					 
class ForEachDemo { public static void main(String s[]) { int array1[]={11,12,13,14,15,16,17,18,19,20}; int sum=0; for(int i:array1) { System.out.println("Value of i is : "+i); sum=sum+i; } System.out.println("Addition : "+sum ); } }


Output

C:\JavaProgram>javac ForEachDemo.java

C:\JavaProgram>java ForEachDemo
Value of i is : 11
Value of i is : 12
Value of i is : 13
Value of i is : 14
Value of i is : 15
Value of i is : 16
Value of i is : 17
Value of i is : 18
Value of i is : 19
Value of i is : 20
Addition : 155

 

 



 

Latest Tutorial


Most Visited Tutorial