News:

GinGly.com - Used by 85,000 Members - SMS Backed up 7,35,000 - Contacts Stored  28,850 !!

Main Menu

Array Types In Java

Started by VelMurugan, Nov 21, 2008, 09:57 PM

Previous topic - Next topic

VelMurugan

Multi-dimensional arrays

So far we have studied about the one-dimensional and two-dimensional arrays. To store data in more dimensions a multi-dimensional array is used. A multi-dimensional array of dimension n is a collection of items. These items are accessed via n subscript expressions. For example, in a language that supports it, the element of the two-dimensional array x is denoted by x[i,j].

The Java programming language does not really support multi-dimensional arrays. It does, however, supports an array of arrays. In Java, a two-dimensional array ' x' is an array of one-dimensional array : For instance :-

                                                                                       int[][] x = new int[3][5];

The expression x is used to select the one-dimensional array; the expression x[j] is ued to select the element from that array. The first element of this array will  be indexed with the "0" value and the last integer will be referenced by "length-1" indexed value. There is no array assignment operator.

Two-dimensional arrays


Two-dimensional arrays are defined as "an array of arrays". Since an array type is a first-class Java type, we can have an array of ints, an array of Strings, or an array of Objects. For example, an array of ints will have the type int[]. Similarly we can have int[][], which represents an "array of arrays of  ints". Such an array is said to be a two-dimensional array.

The command

                   int[][] A = new int[3][4]

declares a variable, A, of type int[][], and it initializes that variable to refer to a newly created object. That object is an array of arrays of ints. Here, the notation int[3][4] indicates that there are 3 arrays of ints in the array A, and that there are 4 ints in each of those arrays.

To process a two-dimensional array, we use nested for loops. We already know about for loop. A loop in a loop is called a Nested loop. That means we can run another loop in a loop.

Notice in the following example how the rows are handled as separate objects.

Code: Java
int[][] a2 = new int[10][5];
// print array in rectangular form
for (int r=0; r<a2.length; r++) {
     for (int c=0; c<a2[r].length; c++) {
         System.out.print(" " + a2[r][c]);
     }
     System.out.println("");
}


In this example, "int[][] a2 = new int[10][5];" notation shows a two-dimensional array. It declares a variable a2 of type int[][],and it initializes that variable to refer to a newly created object. The notation int[10][5] indicates that there are 10 arrays of ints in the array a2, and that there are 5 ints in each of those arrays.