Source of TestArrays.java


  1: //TestArrays.java
  2: 
  3: import java.util.Arrays;
  4: 
  5: public class TestArrays
  6: {
  7:     public static void main(String args[])
  8:     {
  9:         //One-dimensional array initialization and processing loops
 10:         int[] a1 = {1, 3, 5, 7, 9};  //OK, and recommended
 11:         int a2[] = {2, 4, 6, 8, 10}; //OK, but not recommended
 12:         //int[5] a3 = {2, 4, 6, 8, 10};  //illegal
 13:         //int a4[5] = {2, 4, 6, 8, 10};  //illegal
 14:         for (int i=0; i<a1.length; i++) System.out.print(a1[i] + " ");
 15:         System.out.println();
 16:         for (int entry: a2) System.out.print(entry + " ");
 17:         System.out.println();
 18: 
 19:         //Illustrates sort() method of the Arrays class
 20:         int[] b = {6, 2, 8, 10, 4};
 21:         Arrays.sort(b);
 22:         for (int entry: b) System.out.print(entry + " ");
 23:         System.out.println();
 24: 
 25:         //Declare, initialize and display a rectangular two-dimensional array
 26:         int [][] twoDimArray1 = { {1, 2, 3}, {4, 5, 6}};
 27:         for (int row = 0; row < 2; row++)
 28:         {
 29:             for (int col = 0; col < 3; col++)
 30:                 System.out.print(twoDimArray1[row][col] + " ");
 31:             System.out.println();
 32:         }
 33: 
 34:         //Declare, initialize and display a jagged two-dimensional array
 35:         int [][] twoDimArray2 = { {1, 2}, {3, 4, 5, 6}, {7, 8, 9} };
 36:         for (int row = 0; row < twoDimArray2.length; row++)
 37:         {
 38:             for (int col = 0; col < twoDimArray2[row].length; col++)
 39:                 System.out.print(twoDimArray2[row][col] + " ");
 40:             System.out.println();
 41:         }
 42:     }
 43: }
 44: