Saturday, June 26, 2010

A simple Java code to understand Multy Dimensional Arrays

Here we create a three dimensional array and see how it stores values. Once you copy the code and compile it as a java code and run it you will have so many printed outputs on your command prompt. Then you can compare the printed lines with System.out.println(); lines of the code.


class TestArrays{

public static void main(String[] args){


int[][][] x = new int[3][][];
x[0] = new int[2][];
x[0][0] = new int[3];
x[0][0][0] = 10;
x[0][0][1] = 20;
x[0][0][2] = 30;
x[0][1] = new int[]{40, 50, 60, 70};
x[1] = new int[][]{{80}, {90, 100}};
x[2] = new int[1][];
int[] y = {110, 120, 130, 140, 150};
x[2][0] = y;
System.out.println(x[0].length);
System.out.println(x[1].length);
System.out.println(x[2].length);


System.out.println("");


System.out.println(x[0][0].length);
System.out.println(x[0][1].length);


System.out.println("");


System.out.println(x[0][0][0]);
System.out.println(x[0][0][1]);
System.out.println(x[0][0][2]);


System.out.println("");




System.out.println(x[0][1][0]);
System.out.println(x[0][1][1]);
System.out.println(x[0][1][2]);
System.out.println(x[0][1][3]);






System.out.println("");


System.out.println(x[1].length);
System.out.println(x[1][0].length);
System.out.println(x[1][1].length);


System.out.println("");


System.out.println(x[1][0][0]);
System.out.println(x[1][1][0]);
System.out.println(x[1][1][1]);


System.out.println("");


System.out.println(x[2].length);


System.out.println("");


System.out.println(x[2][0].length);


System.out.println("");


System.out.println(x[2][0][0]);
System.out.println(x[2][0][1]);
System.out.println(x[2][0][2]);
System.out.println(x[2][0][3]);
System.out.println(x[2][0][4]);


}
}

No comments:

Post a Comment