Enhanced for loop in Java


The enhanced style for can only cycle through an array sequentially, from start to finish.It is also known as the enhanced for loop. The enhanced for loop was introduced in Java 5 as a simpler way to iterate through all the elements of a Collection (Collections are not covered in these pages). It can also be used for arrays, as in the above example, but this is not the original purpose.

Enhanced for loops are simple but inflexible. They can be used when you wish to step through the elements of the array in first-to-last order, and you do not need to know the index of the current element.

Syntax:
   for( Datatype item : array )
   {
        // body of loop;
   }

  Datatype : The Datatype of the array/collection
  Item : Each item of array/collection is assigned to this variable
  Array : An array or a collection

This is a Java program that uses an enhanced for loop to iterate through an array of integers and print each element to the console. Here's a breakdown of how the program works:

  • We declare a class called "Enhanced_for".
  • We define a main method that takes an array of strings as its parameter.
  • We create an array of integers called "numbers" and initialize it with the values 10, 20, 30, 40, 50, 60, and 70.
  • We use an enhanced for loop to iterate through each element in the "numbers" array.
  • For each element in the array, we declare an integer variable called "n" and assign it the value of the current element.
  • We then print the value of "n" to the console using the System.out.println method.
  • The loop continues until all elements in the "numbers" array have been printed.

Overall, this program demonstrates how to use an enhanced for loop to iterate through an array and perform a task on each element.

Source Code

public class Enhanced_for {
    public static void main(String args[])
    {
        int numbers[]={10,20,30,40,50,60,70};
        for(int n : numbers)
        {
            System.out.println(n);
        }
    }
}
 

Output

10
20
30
40
50
60
70
To download raw file Click Here

Basic Programs