two Dimensioanl Array in Java
Java, supports multi-dimensional arrays - 1-dimensional, 2-dimensional, 3-dimensional. But we mostly use one and two dimensional arrays. Use of the 3 d and more dimensional array is rare. But once you understand the concept of the 2-dimensional array, you can extend the concept for 3 or more dimension case as well.
You can visualize a 2-dimensional array as a table with rows and columns. From machine perspective the row and colunms are just ideas as they do nor exist in reality. What happens on a machine is - we store the first row followed immediately by the second row and so on - in a linear fashion. We call a 2-dimensional array as an Array of Array.
The example below shows a two dimensional array, where a student records the number of hours he studied in each of the three weeks. We then calculate the total number of hours read by the student.
|
If you compile and run, you get the following output
Total Hours Read = 34 |
A 2x3 dimensional array x[2][3] can me mentally thought of as being composed of two rows an three columns.
Table: A two dimensional array x[2][3]
x[0][0] | x[0][1] | x[0][2] |
x[1][0] | x[1][1] | x[1][2] |
Alternate way of Initializing Array
A two dimensional array could also be initialized as
int [][]x ={ {3,2,1},{2,2,2}}
Which is essentially a 2x3 array.
The following example initializes and prints the array in this fashion.
A two dimensional array could also be initialized as int [][]x ={ {3,2,1},{2,2,2}} Which is essentially a 2x3 array.
The following example initializes and prints the array in this fashion.
|
If you compile and run, you get the following output
a[0][0] = 3 a[0][1] = 2 a[0][2] = 1 a[1][0] = 2 a[1][1] = 2 a[1][2] = 2 |
It is perfectly legat to have different sizes of the column. For example, it is legal to declare
int [][]x ={ {7,2,4},{2,2}, {2}} ;