Legal and illegal enhanced for declarations : enhanced for loop « Statements « SCJP






public class MainClass {
  public static void main(String[] argv) {
    int x;
    long x2;
    Long[] LongArray = { 4L, 5L, 6L };
    long[] longArray = { 7L, 8L, 9L };
    int[][] twoDimensionalArray = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
    String[] sNums = { "one", "two", "three" };
    Animal[] animals = { new Dog(), new Cat() };

    for (long y : longArray)
      ;

    for (long lp : LongArray)
      ;
    for (int[] n : twoDimensionalArray)
      ;
    for (int n2 : twoDimensionalArray[2])
      ;
    for (String s : sNums)
      ;
    for (Object o : sNums)
      ;
    for (Animal a : animals)
      ;

    // ILLEGAL 'for' declarations
    // for(x2 : la) ; // x2 is already declared
    // for(int x2 : twoDimensionalArray) ; // can't stuff an array into an int
    // for(int x3 : longArray) ; // can't stuff a long into an int
    // for(Dog d : animals) ; // you might get a Cat!

  }
}

class Animal {
}

class Dog extends Animal {
}

class Cat extends Animal {
}








5.4.enhanced for loop
5.4.1.Enhanced for Loops and array: perform identical processing on every element of an array.
5.4.2.Enhanced array for references.
5.4.3.Legal and illegal enhanced for declarations