Two dimension arrays

Two dimension arrays


Posted in : Core Java Posted on : October 14, 2010 at 3:59 PM Comments : [ 0 ]

This section contains the detail about the Two dimension arrays in java.

Two dimension arrays

In java, multidimensional arrays are actually arrays of arrays. For example, you can declare a two dimensional array as :

int twoD[][]=new int [4][5];

You can also declare a three dimensional array as :

int threeD[][][]= new int [3][4][5];

Example :

Class TwoDmatrix{
  public static void main(String args[]) {
    int twoDm[][]= new int[4][5];
    int i,j,k=0;

    for(i=0;i<4;i++)
      for(j=0;j<5;j++) {
         twoDm[i][j]=k;
         k++;
      }
    for(i=0;i<4;i++)
      for(j=0;j<5;j++) {
         System.out.println(twoDm[i][j]+"")
         System.out.println();
      }
   }
 }
 

Output :

C:\Program Files\Java\jdk1.6.0_18\bin>javac TwoDmatrix .java

C:\Program Files\Java\jdk1.6.0_18\bin>java TwoDmatrix
0  1  2  3  4
5  6  7  8  9
10 11 12 13 14
15 16 17 18 19

You need to specify the memory for the first(leftmost)  dimension for a multidimensional array. Remaining dimensions can be allocated separately. The main advantage is that you need not to allocate the same number of elements for each dimension. For example, the following program creates a two-dimensional array in which the sixe of the second dimension are unequal :


public class DemoTwoD {
	public static void main(String args[]) {
		int DevtwoD[][] = new int[4][];
		DevtwoD[0] = new int[1];
		DevtwoD[1] = new int[2];
		DevtwoD[2] = new int[3];
		DevtwoD[3] = new int[4];

		int a, b,c=0;

		for (a = 0; a < 4; a++)
		    for (b = 0; b < a + 1; b++) {
			DevtwoD[a][b]=c;
			c++;
		}
		for (a = 0; a < 4; a++) {
			for (b = 0; b < a + 1; b++)
			System.out.print(DevtwoD[a][b] + " ");
			System.out.println();
	    }
    }

 }

Output :

C:\Program Files\Java\jdk1.6.0_18\bin>javac DemoTwoD.java

C:\Program Files\Java\jdk1.6.0_18\bin>java DemoTwoD
0
1 2
3 4 5
6 7 8 9  

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics