Multidimensional Array LectureReal
Multidimensional Array LectureReal
Example:
int[][] matrix = new int[3][3];
Initialization Example:
int[][] matrix =
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Accessing Elements:
System.out.println(matrix[0][1]); // Output: 2
2. Three-Dimensional Array (3D Array)
A 3D array is an array of 2D arrays. It can be visualized as a cube or a collection of matrices.
Syntax:
dataType[][][] arrayName = new dataType[x][y][z];
Example:
int[][][] cube = new int[2][3][4];
Initialization Example:
int[][][] cube =
{
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
},
{
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24}
}
};
Accessing Elements:
System.out.println(cube[1][2][3]); // Output: 24
3. Jagged Array
A jagged array is a multidimensional array where the inner arrays can have different lengths. It is also
called a ragged array.
Syntax:
dataType[][] arrayName = new dataType[rows][];
Example:
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[2];
jaggedArray[1] = new int[3];
jaggedArray[2] = new int[1];
Initialization Example:
int[][] jaggedArray =
{
{1, 2},
{3, 4, 5},
{6}
};
Accessing Elements:
System.out.println(jaggedArray[1][2]); // Output: 5
Conclusion
Multidimensional arrays are powerful tools for handling complex data structures in Java.
Understanding how to declare, initialize, and use them effectively is essential for working with grid-
like data, matrices, and dynamic datasets. By mastering multidimensional arrays, you can efficiently
solve problems that involve tabular or multi-layered data.