184. For-each loop

For-each loop is a form of for loop which can be used with arrays. For-each loop iterates for each element of the array.

Example -

int var[ ] = { 1, 2, 3, 4, 5 };

The above array has 5 elements, hence the for-each loop iterates for 5 times (i.e. each time for every element in the array )

Syntax of For-each loop for arrays -

for(data_type variable : array)


Example of For-each loop for arrays -

int var[ ] = { 1, 2, 3, 4, 5 };

for(int x : var )

Observe that in the above for-each loop, the variable x will be assigned 1 (i.e. 1st element of the array).

So, when you are print the array element, as the index of the array starts with 0, mention var[x-1] (i.e.. var[0] ) instead of var[x] (i..e var[1] ).

Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, create a Java Project 'Project 20' as shown below -

2. Create a Java Class 'ForEachLoopDemo' with main( )  method as shown below -

3. Declare an type of array and assign any 5 values to it as shown below -

4. Create a for-each loop to print all the values of the array as shown below -

5. Observe that an error is displayed and view the error as shown below -

6. Though I have installed Java version 1.8 in my machine, the compiler compliance level in Eclipse for the Java Projects is set to a version level that is less than 1.5 and for-each loop feature is introduced in Java from version 1.5. Hence this error is displayed. To resolve this error select 'Change Project compliance and JRE to 1.5' option displayed in the error message as shown below  -

7. Observe that the error got resolved as shown below -

8. Run the Class and observe that all the 5 values stored the array are displayed as output in the console as shown below -

Notes -

  1. For-each loop can also be used with varargs ( varargs concept will be explain in the next post)
  2. For-each loop can also be used with collections (collections concept will be explained later in this blog) 

Please comment below to feedback or ask questions.

varargs 'Variable Length Arguments' will be explained in the next post.

No comments: