Two-dimensional arrays

Ads
 

Two-dimensional arrays

In this section, you will learn about two-dimensional arrays with an example.`

In this section, you will learn about two-dimensional arrays with an example.`

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 i=0; i<a2.length; i++) {
     for (int j=0; j<a2[i].length; j++) {
         System.out.print(" " + a2[i][j]);
     }
     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. 

Here is the complete code of the example:

public class twoDimension{
  public static void main(String[] args) {
  int[][] a2 = new int[10][5];
  for (int i=0; i<a2.length; i++) {
  for (int j=0; j<a2[i].length; j++) {
  a2[i][j= i;
  System.out.print(" " + a2[i][j]);
  }
  System.out.println("");
  }
  }
}

Here is the output for the program:

C:\tamana>javac twoDimension.java
C:\tamana>java twoDimension
 0 0 0 0 0
 1 1 1 1 1
 2 2 2 2 2
 3 3 3 3 3
 4 4 4 4 4
 5 5 5 5 5
 6 6 6 6 6
 7 7 7 7 7
 8 8 8 8 8
 9 9 9 9 9
C:\tamana>_

Download this program

Ads

Ads