for each loop

The new version eliminates the loop counter.

The new syntax is:


for (type variable_name:array){
       
}

The type must be compatible with the array type.


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);
    }
  }
}

The output:


java2s.com
a
b
c

Use for-each style for on a two-dimensional array.

 
public class Main {
  public static void main(String args[]) {
    int sum = 0;
    int nums[][] = new int[3][5];
    // give nums some values
    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:


Value is: 1 
Value is: 2 
Value is: 3 
Value is: 4 
Value is: 5 
Value is: 2 
Value is: 4 
Value is: 6 
Value is: 8 
Value is: 10 
Value is: 3 
Value is: 6 
Value is: 9 
Value is: 12 
Value is: 15 
Summation: 90

// Search an array using for-each style for. 
public class Main {
  public static void main(String args[]) {
    int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 };
    int val = 5;
    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!");
  }
}
Home 
  Java Book 
    Language Basics  

Statement:
  1. Simplest if statement
  2. If else statement
  3. switch statement
  4. while loop
  5. do-while statement
  6. for Loop
  7. for each loop
  8. break to Exit a Loop
  9. continue
  10. return statement returns from a method.
  11. Comments