Java Tutorial - 25 Array (2-Dimensional Array)in Java - Study Viral
2D (or 2 Dimensional Array)
Two-dimensional arrays are arrays of arrays.
Initializing two-dimensional arrays:
int[][] arr1 = new int[3][3];
The 1st dimension represent rows or number of one dimension, the 2nd dimension represent columns or number of elements in the each one dimensions.
int[][] arr2 = { {1,2,3}, {4,5,6}, {7,8,9} };
int[][] arr3 = new int[][] { {1,2,3}, {4,5,6}, {7,8,9} };
int[][] arr4 = new int[3][] { {1,2,3}, {4,5,6}, {7,8,9} };//error
You can initialize the row dimension without initializing the columns but not vice versa
int[][] x = new int[3][];
int[][] x = new int[][3]; //error
The length of the columns can vary for each row and initialize number of columns in each row.
int [][]x = new int [2][];
x[0] = new int[5];
x[1] = new int [5];
int [][]x = new int [3][];
x[0] = new int[]{0,1,2,3};
x[1] = new int []{4,5,6};
x[2] = new int[]{7,8,9,10,11};
Jagged array is array of arrays such that member arrays can be of different sizes,
i.e., we can create a 2-D arrays but with variable number of columns in each row.
These type of arrays are also known as Jagged arrays.
int x[] = {1, 2, 3};
int y[] = {6, 5, 4};
int z[] = {9, 8, 7};
int c[][]={x, y, z};
0 comments:
Post a Comment