Scanner class Methods in Java

Java - Enhanced for loop

 Enhanced for Loop

When Java 1.5 was released, it introduced a new feature know as enhanced for loop. The working of enhanced for loop is same as for loop.But it has very simple syntax.This loop is best suited to access the elements of array.But other operations like reading values or getting values require conventional for loop.

Syntax:

for(datatype variableName : collectionName)

{

//statement(s)

}

The dataype is used to specify the dataype of loop control variable e.g int in the for loop. It can be of any data typewith respect to dataype of collection or array The variableName is the name of variable like , i ,j,k etc. The colon(:) symbol is must to be used in syntax. Then the collectionName is the collection or group whom we want to traverse like arrayName.

Example:

for(int i : myArray)

System.out.println(i);

This will exactly work like for loop. In the example, we are printing the array element present at index i.

Note: When we have only one statement to execute in any control statement like if , else or loops, we can omit curly brackets {}.Check the example given above.

Lets create a program to understand  the use of enhanced for loop.

Write a program to print a series containing multiples of 3 using enhanced for loop.

Enhanced for loop Write a program to print a series containing multiples of 3.
In the example above,
  1. We created an array and got its value from user.If you want to know, how to get value of array from user, read  Arrays .
  2. To get values from user, we used simple for loop.Because we have to add condition to get value till "num" number.When num=5 , only 5 numbers can be entered by user.If user enters more than 5 numbers then a runtime error  "ArrayIndexOutOfBounds"  will be thrown.
  3. To print array elements we can use enhanced for loop. The enhanced loop will iterate through the whole array entered by user. The "if" statement's test condition is dividing each element present at index "i" with 3 and compares remainder with 0. If remainder is 0 the element is multiple of 3 and gets printed on screen.
Output:

enhanced for loop
Experiment: Try printing series divisible by 5.

Happy Coding!



Comments