Source of TestArrays.java


  1: // TestArrays.java
  2: // Tests various ways of initializing an array.

  4: class TestArrays
  5: {
  6:     public static void main(String[] args)
  7:     {
  8:         //int[] a = { 2, 4, 6, 8, 10 };  // OK
  9:         //int a[] = { 2, 4, 6, 8, 10 };  // OK
 10:         //int[] a = new int[] {0, 2, 4, 6, 10}; // OK

 12:         //int[5] a = { 2, 4, 6, 8, 10 };   // Compile error
 13:         //int[] a = new int[5] {0, 2, 4, 6, 10}; // Compile error
 14:         //int[] a = new int {0, 2, 4, 6, 10}; // Compile error
 15: /*        for (int i=0; i<a.length; i++)
 16:             System.out.print(a[i]+" ");
 17:         System.out.println();
 18: */
 19:         //int[] numbers = { 1, 2, 3, 4 };  // Typical initialization

 21:         //int numbers[] = { 1, 2, 3, 4 };  // Also works

 23: /*        final int SIZE = 4;
 24:         int[] numbers = new int[SIZE];
 25:         for (int i=0; i<SIZE; i++)
 26:             numbers[i] = i+1;

 28:         for (int i=0; i<numbers.length; i++)
 29:             System.out.println(numbers[i]);
 30: */
 31:         // Declare and initialize an array of 2 rows and 7 columns
 32:         int [][] temperatures =
 33:             { { 15, 17, 19, 17, 22, 24, 18 },
 34:               { 18, 20, 20, 19, 24, 25, 25 } };
 35:         final int NUM_ROWS = 2;
 36:         final int NUM_COLS = 7;
 37:         // Typical two-dimensional array access
 38:         for (int row=0; row<NUM_ROWS; row++)
 39:             for (int col=0; col<NUM_COLS; col++)
 40:                 System.out.println(temperatures[row][col]);
 41:         System.out.println(temperatures[1].length);

 43: /*        int[] a = new int[4];
 44:         for (int i=0; i<4; i++) System.out.println(a[i]);
 45: */   }
 46: }