2-dimensional arrays are usually represented in a row-column approach on paper, and the terms "rows" and "columns" are used in computing.
Arrays of arrays

There are two ways to implement 2-dimensional arrays. Many languages reserve a block of memory large enough to hold all elements of the full, rectangular, array (number of rows times number of columns times the element size). Java doesn't do this. Instead Java builds multi-dimensional arrays from many one-dimensional arrays, the so-called "arrays of arrays" approach. [C++ supports both styles.]

There are a couple of interesting consequences of this: Rows may be different sizes. Also, each row is an object (an array) that can be used independently.

Declaration

Declare a 2-dimensional array as follows:

Code: Java

int[][] a2; // Declares, but doesn't allocate, 2-dim array.

Allocation

As with all arrays, the new keyword must be used to allocate memory for an array. For example,

Code: Java

int[][] a2 = newint[10][5];

This allocates an int array with 10 rows and 5 columns. As with all objects, the values are initialized to zero (unlike local variables which are uninitialized).

This actually allocates 6 objects: a one-dimensional array of 5 elements for each of the rows, and a one-dimensional array of ten elements, with each element pointing to the appropriate row array.

Processing 2-dimensional arrays

Often 2-dimensional arrays are processed with nested for loops. Notice in the following example how the rows are handled as separate objects. For example,

You can use simple sorting algorithms like Bubble Sort,Selection Sort to sort the array data. Multi-dimensional array concepts can be applied to two-dimensional arrays. You are free to ask any specific questions you have about two-dimensional arrays.