Arrays (Cont.)


Looping Through an Array with For-Each
There is also a “for-each” loop, which is used exclusively to loop through elements in arrays. The following example outputs all elements in the cars array, using a “for-each” loop. The example can be read like this: for each String element (called i - as in index) in cars, print out the value of i. If you compare the for loop and for-each loop, you will see that the for-each method is easier to write, it does not require a counter (using the length property), and it is more readable.

 String[ ] cars = { "Volvo", "BMW", "Ford", "Mazda" };
 for ( String i : cars )   System.out.println( i );

Multidimensional Arrays
A multidimensional array is an array containing one or more arrays. To create a two-dimensional array, add each array within its own set of curly braces. myNumbers is now an array with two arrays as its elements. To access the elements of the myNumbers array, specify two indexes: one for the array, and one for the element inside that array. This example accesses the third element (2) in the second array (1) of myNumbers:

 int[ ][ ] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
 int x = myNumbers[1][2];
 System.out.println( x );     // Output: 7

We can also use a for loop inside another for loop to get the elements of a two-dimensional array (we still have to point to the two indexes):

  public class MyClass {
    public static void main( String[ ] args ) {
      int[ ][ ] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
      for ( int i = 0; i < myNumbers.length; ++i )
        for ( int j = 0; j < myNumbers[i].length; ++j )
          System.out.println( myNumbers[i][j] );
    } 
  }               // Output: 1234567




      The best way to predict the future is to create it.