Saturday, November 14, 2015

Java - foreach Loop

Foreach loop is a feature that has been present in many languages like Perl, Ruby etc for some time. Java finally implemented it in Java 5. The official documents refer to this new loop as the "Enhanced for Loop", the "For-Each Loop" and the "foreach statement".

To ensure that existing code is not broken, it was decided that a new keyword will not be introduced. The changes were done in the syntax of the for keyword.

Syntax:
for (declaration : expression) {
    // Statements (generally using the variable declared above)
}

An example of usage is as follows:
public class NewFor1 {
 public static void main(String[] args) {
  int[] arr = {100, 200, 300, 400, 500};

  for (int i:arr) {
   System.out.println(i);
  }
 }
}

This code generates the following output:
$ javac NewFor1.java
$ java NewFor1
100
200
300
400
500

As you can see, the program NewFor.java is a toy program. Generally, this loop is used while iterating over a Collection.

A couple of caveats:
Caveat 1. The first part of the for loop has to be a declaration.
public class NewFor2 {
 public static void main(String[] args) {
  int i = 0;
  int[] arr = {100, 200, 300, 400, 500};

  for (i:arr) {
   System.out.println(i);
  }
 }
}

$ javac NewFor2.java 
NewFor2.java:6: error: not a statement
  for (i:arr) {
       ^
NewFor2.java:6: error: ';' expected
  for (i:arr) {
        ^
NewFor2.java:6: error: ';' expected
  for (i:arr) {
         ^
3 errors
$
This syntax makes sense because the primary purpose of this loop is to make it easy to iterate through a collection. In such a case, declaring the variable in this place makes the most sense.

Caveat 2. What does the normal for loop provide that the foreach loop does not provide?
Answer: The index. While for loop provides an index which can also be used in the statements enclosed within the loop, the index cannot be obtained directly in the foreach loop.

Post a Comment