Java Array for each loop

In this chapter you will learn:

  1. How to use for each loop with Java array
  2. Syntax for array for each loop
  3. Example - 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  w w.  j  av  a2  s  .  c om
    }
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How is the multidimensional arrays stored
  2. Syntax for Java Multidimensional Arrays
  3. Example - Java Multidimensional Arrays
  4. Example - How to create a three-dimensional array
  5. What are Jagged array
  6. Example - Jagged array
  7. How to initialize multidimensional arrays during declaration
Home »
  Java Tutorial »
    Java Langauge »
      Java Array
Java Array
Java Array Variables
Java Array Initial Values
Java Array Length
Java Initialize Arrays
Java Array Index
Java Array for each loop
Java Multidimensional Arrays