Chapter 9: Arrays

The exercises here are taken from my forthcoming book, The Java Developer's Resource.

Quiz

  1. What's the index of the first component of a one hundred component array? of a two hundred component array? of a one thousand and twenty-four component array?

    The index of the first component of an array is always 0.

  2. What's the index of the last component of a one hundred component array? of a two hundred component array? of a one thousand and twenty-four component array?

    99, 199, and 1023 respectively. The index of the last component of an array is always one less than the length of the array.

  3. What's the mininum number of components an array can have?

    An array can have as few as zero components; that you can declare an array with no components at all. However you cannot declare an array with a negative number of components. If you try, a java.lang.NegativeArraySizeException will be thrown at runtime.

  4. What's the difference between a brace and a bracket?

    { or } is a brace. [ or ] is a bracket. Braces are used to initialize arrays. Brackets are used to select a component of an array by specifying its index.

Exercises

  1. Write a program that randomly fills a 3 by 4 by 6 array, then prints the largest and smallest values in the array.

    
    class array346 {
    
      public static void main(String[] args) {
    
        double[][][] array = new double[3][4][6];
        
        for (int i = 0; i < 3; i++) {
          for (int j = 0; j < 3; j++) {
            for (int k = 0; k < 3; k++) {
              array[i][j][k] = Math.random();
            }
          }
        }
      
        double max = array[0][0][0];
        double min = array[0][0][0];
        
        for (int i = 0; i < 3; i++) {
          for (int j = 0; j < 3; j++) {
            for (int k = 0; k < 3; k++) {
              if (max < array[i][j][k]) max = array[i][j][k];
              if (min > array[i][j][k]) min = array[i][j][k];
            }
          }
        }
    
        System.out.println("Maximum: " + max);
        System.out.println("Minimum: " + min);
    
      }
      
    }


[ Exercises | Cafe Au Lait | Books | Trade Shows | Links | FAQ | Tutorial | User Groups ]

Copyright 1996 Elliotte Rusty Harold
elharo@sunsite.unc.edu
Last Modified August 21, 1996