Two Dimensional Arrays in Java

Declaring, Allocating and Initializing Two Dimensional Arrays:
Two dimensional arrays are declared, allocated and initialized much like one dimensional arrays. However we have to specify two dimensions rather than one, and we typically use two nested for loops to fill the array. for

The array examples above are filled with the sum of their row and column indices. Here's some code that would create and fill such an array:

class FillArray {
  public static void main (String args[]) {
    int[][] M;
    M = new int[4][5];
    for (int row=0; row < 4; row++) {
      for (int col=0; col < 5; col++) {
        M[row][col] = row+col;
      }
    }
  }
}

In two-dimensional arrays ArrayIndexOutOfBounds errors occur whenever you exceed the maximum column index or row index. Unlike two-dimensional C arrays, two-dimensional Java arrays are not just one-dimensional arrays indexed in a funny way.

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More