Java for each loop

In this chapter you will learn:

  1. What is Java for each loop
  2. How to write for each loop
  3. Example - for each loop
  4. Example - for-each style loop to iterate a two-dimensional array
  5. Example - search an array element with for each loop

Description

The for each loop iterates elements in a sequence without using the loop counter.

Syntax

The syntax of for each loop is:


for (type variable_name:array){
       
}

The type must be compatible with the array type.

Example


public class Main {
  public static void main(String args[]) {
    String[] arr = new String[]{"java2s.com","a","b","c"};
    for(String s:arr){
      System.out.println(s);/* w ww  . ja  v a 2s .co  m*/
    }
  }
}

The output:

Example 2

The following code uses the for-each style loop to iterate a two-dimensional array.


public class Main {
  public static void main(String args[]) {
    int sum = 0;//from   ww w  .j a v a 2 s.c o m
    int nums[][] = new int[3][5];
    for (int i = 0; i < 3; i++){
      for (int j = 0; j < 5; j++){
        nums[i][j] = (i + 1) * (j + 1);
      }  
    }
    // use for-each for to display and sum the values
    for (int x[] : nums) {
      for (int y : x) {
        System.out.println("Value is: " + y);
        sum += y;
      }
    }
    System.out.println("Summation: " + sum);
  }
}

The output from this program is shown here:

Example 3

for-each style loop is useful when searching an element in an array.


public class Main {
  public static void main(String args[]) {
    int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 };
    int val = 5;//from w ww  . j a  va  2s  . c om
    boolean found = false;
    // use for-each style for to search nums for val
    for (int x : nums) {
      if (x == val) {
        found = true;
        break;
      }
    }
    if (found)
      System.out.println("Value found!");
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What is Java while loop
  2. How to use the basic Java While Loop
  3. Note for Java while Loop
  4. Example - Java while loop
  5. Example - while condition
  6. Example - while loopbody
Home »
  Java Tutorial »
    Java Langauge »
      Java Statement
Java if Statement
Java if else Statement
Java if else ladder statement
Java nested if statement
Java switch Statement
Java for loop
Java for each loop
Java while Loop
Java do while loop
Java break statement
Java continue statement
Java Comments
Java documentation comment(Javadoc)