Java-Get Array Values Using For-Each

Get Array Values Using For-Each Loop

The for each loop helps us to retrieve the array of elements efficiently rather than using array indexes. This loop is designed to cycle through the entire array, obtaining one element at a time, in sequence, from beginning to end. The loop traverses the elements of the array, not the index values. For example, in the following program, with each pass through the loop, x is automatically given a value equal to the next element in values. Thus, on the first iteration, x contains 10; on the second iteration, x contains 20; and soon. Not only is the syntax streamlined, but it also prevents boundary errors.

Program

Program Source

public class Javaapp {
 
    public static void main(String[] args) {
     
        int[] values = {10,20,30,40,50}:
     
        for(int x:values)
        {
            System.out.println(x);
        }
    }
}

Leave a Comment