Java Array for each loop

Description

We can use a collection-based for loop as an alternative to the numerical for loop when processing the values of all the elements in an array.

Syntax

The syntax of for each loop for an array is as follows.


for(arrayType variableName: array){
  process each variableName
}

Example

Java array for each loop


public class Main {
  public static void main(String args[]) {
    int days[] = {1, 2, 3,};
    for(int i:days){
      System.out.println(i);/*w  ww .  j a v  a2  s .  co  m*/
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures