Access 3D Arrays
Master 3D array element access: A[layer][row][column] syntax, zero-based indexing from A[0][0][0] to A[D-1][N-1][M-1]. Learn safe element modification and ArrayIndexOutOfBoundsException handling with practical examples.
How do you access elements?
Following is a simple sketch of a 3D array A
with a capacity of D layers, N rows, and M columns.
int[][][] A;
Visual representation
A[layer][row][column]
↓ ↓ ↓
depth rows columns
Since arrays in Java start from the 0th index in all dimensions:
- If you want to access the first element, you need to use
A[0][0][0]
- To access an element at layer 1, row 2, column 1:
A[1][2][1]
- To access the last element in a D×N×M array:
A[D-1][N-1][M-1]
What happens with invalid indexes?
What happens if we try A[3][2][1]
, A[1][5][2]
, or A[2][1][4]
in a 2×3×3 array? 🤔
You guessed it. We run into ArrayIndexOutOfBoundsException
.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 2
at ThreeDimensionalArray.main(ThreeDimensionalArray.java:15)
You can access and modify individual elements in a 3D array using the layer, row, and column indexes.
For example, to access the element at layer 1, row 2, and column 1 of the "cube" array:
int element = A[1][2][1];
Similarly, you can assign a value to an element in the array:
A[1][2][1] = 42;
At most, we can access the last element of the array using A[D-1][N-1][M-1]
.