Skip to main content
Lesson 21 - Two Dimensional Arrays
ZIPPDF (letter)
Lesson MenuPreviousNext
  
Passing Two-Dimensional Arrays to Methods page 4 of 9

  1. The following program will illustrate parameter passing of an array. The purpose of this program is to read a text file containing integer data, store it in a 2-D array, and print it out. The contents of the text file "data.txt" is shown first:

    "data.txt"
    
        17   3   2  13
         5  10  11   8
         9   6   7  12
         4  15  14   1

    Program 21-3

    // A program to illustrate 2D array parameter passing
    
    import chn.util.*;
    import apcslib.*;
    
    class Test2D
    {
      public void printTable (int[][] pTable)
      {
        for (int row = 0; row < pTable.length; row++)
        {
          for (int col = 0; col < pTable[row].length; col++)
            System.out.print(Format.right(pTable[row][col], 4));
          System.out.println();
        }
      }
      
      public void loadTable (int[][] lTable)
      {
        FileInput inFile = new FileInput("data.txt");
        
        for (int row = 0; row < lTable.length; row++)
          for (int col = 0; col < lTable[row].length; col++)
            lTable[row][col] = inFile.readInt();
      }
      
      public static void main (String[] args)
      {
        final int MAX = 4;
        
        int[][] grid = new int[MAX][MAX];
    
        Test2D test = new Test2D();
        
        test.loadTable(grid);
        test.printTable(grid);
      }
    }
  2. The loadTable and printTable methods each use a reference parameter, (int[][] lTable and int[][] pTable respectively). The local identifiers lTable and pTable serve as aliases for the actual parameter grid passed to the methods.

  3. When a program is running and it tries to access an element of an array, the Java virtual machine checks that the array element actually exists. This is called bounds checking. If your program tries to access an array element that does not exist, the Java virtual machine will generate an ArrayIndexOutOfBoundsException exception. Ordinarily, this will halt your program.


Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.