Today we will look into Two-dimensional array in java. An array is like a container that can hold a certain number of values.
Two Dimensional Array in Java
Let’s look at a few examples of defining java two-dimensional array or 2d array.
Java Two Dimensional Array of primitive type
1 2 3 4 5 6 7 8 9 10 |
int[][] arr = new int[2][3]; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { arr[i][j] = j; System.out.print(arr[i][j] + " "); } System.out.println(""); } |
Java Two Dimensional Array of Objects
1 2 3 4 5 6 7 8 9 10 |
String[][] arrStr = new String[3][4]; for (int i = 0; i < arrStr.length; i++) { for (int j = 0; j < arrStr[i].length; j++) { arrStr[i][j] = "Str" + j; System.out.print(arrStr[i][j] + " "); } System.out.println(""); } |
So we can define a two dimensional array of primitive data types as well as objects. If you look at the above examples, two dimensional array looks like a matrix, something like below image.
However, in Java, there is no concept of a two-dimensional array. A two-dimensional array in java is just an array of array. So below image correctly defines two-dimensional array structure in java.
Java multidimensional array example
Now if two-dimensional array in java is an array-of-arrays, then it should also support non-symmetric sizes as shown in below image.
Well, it’s absolutely fine in java. Below is an example program that depicts above multidimensional array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public class MultidimensionalArrayExample { public static void main(String[] args) { // creating and initializing two dimensional array with shortcut syntax int[][] arrInt = { { 1, 2 }, { 3, 4, 5 } }; for (int i = 0; i < arrInt.length; i++) { for (int j = 0; j < arrInt[i].length; j++) { System.out.print(arrInt[i][j] + " "); } System.out.println(""); } // showing multidimensional arrays initializing int[][] arrMulti = new int[2][]; // yes it's valid arrMulti[0] = new int[2]; arrMulti[1] = new int[3]; arrMulti[0][0] = 1; arrMulti[0][1] = 2; arrMulti[1][0] = 3; arrMulti[1][1] = 4; arrMulti[1][2] = 5; for (int i = 0; i < arrInt.length; i++) { for (int j = 0; j < arrInt[i].length; j++) { System.out.print(arrInt[i][j] + " "); } System.out.println(""); } } } |
If we run the above program, it will produce the following output.
1 2 3 4 5 6 |
<span style="color: #008000;"><strong><code> 1 2 3 4 5 1 2 3 4 5 </code></strong></span> |
That’s all about two-dimensional array in java. In a similar way, we can define a multidimensional array in java too.
Reference: Java Array Oracle page