1. Introduction to a Three-Dimensional Array
Premium Video
This video is available to Premium members or users who have purchased the course.
Sign in to UnlockA three-dimensional array (3D array) is an array that uses three indexes to access an element. You can think of it as a collection of 2D arrays, or as a group of layers, where each layer contains rows and columns.
For example:
Layer 0
| 10 | 20 |
|---|---|
| 30 | 40 |
Layer 1
| 50 | 60 |
|---|---|
| 70 | 80 |
This example has 2 layers, 2 rows in each layer, and 2 columns in each row. It contains \(2 \times 2 \times 2 = 8\) elements.
In Java, multidimensional arrays are arrays of arrays. Therefore, different layers or rows can have different lengths; a 3D array does not have to be a perfect rectangular block.
Learning objectives
By the end of this article, you will be able to:
- Declare and create a 3D array.
- Initialize it with nested braces.
- Access and update an element using three indexes.
- Traverse all elements using three nested loops.
- Understand what each
lengthexpression returns. - Recognize 3D arrays whose rows have different lengths.
- Follow a flowchart for safe, complete traversal.
2. Declaring a 3D Array
The declaration syntax is:
For example:
The three pairs of square brackets indicate three levels of array structure. This statement declares a reference variable; it does not yet create the array.
3. Creating a 3D Array
Use the new keyword to create an array with a specified number of layers, rows, and columns.
This creates:
- 2 layers
- 2 rows in each layer
- 2 integer elements in each row
The total number of elements in this rectangular array is:
\[ 2 \times 2 \times 2 = 8 \]Because the elements are of type int, each element initially contains 0.
Complete runnable example
Expected output
Layers: 2
Rows in layer 0: 2
Columns in layer 0, row 0: 2
Default value: 0
Understanding length
| Expression | Meaning |
|---|---|
numbers.length | Number of layers |
numbers[i].length | Number of rows in layer i |
numbers[i][j].length | Number of elements in row j of layer i |
The last two expressions refer to a particular layer and row, so those indexes must refer to existing, non-null arrays.
4. Initializing a 3D Array
You can provide values directly with nested braces:
The outer braces contain the layers. Each layer contains row arrays, and each row contains integer values.
Complete runnable example
Expected output
Layer 0, row 0: 10 20Layer 1, row 1: 70 80
5. Accessing Elements in a 3D Array
Use three indexes to select an element:
- The first index selects the layer.
- The second index selects a row within that layer.
- The third index selects an element within that row.
For the initialized array above:
| Expression | Meaning | Value |
|---|---|---|
numbers[0][0][0] | Layer 0, row 0, column 0 | 10 |
numbers[0][1][0] | Layer 0, row 1, column 0 | 30 |
numbers[1][0][1] | Layer 1, row 0, column 1 | 60 |
numbers[1][1][1] | Layer 1, row 1, column 1 | 80 |
All indexes start at 0.
Complete runnable example
Expected output
1080
6. Updating an Element
To change an element, assign a new value to its layer, row, and column position.
For example, numbers[0][1][0] = 100; updates layer 0, row 1, column 0. The old value at that position is 30.
Complete runnable example
Expected output
Updated value: 100Only the selected element changes; the other values remain the same.
7. Traversing a 3D Array Using Three Nested Loops
Traversal means visiting each element. For a 3D array, three nested loops are commonly used:
- The outer loop moves through the layers.
- The middle loop moves through the rows in the current layer.
- The inner loop moves through the elements in the current row.
Complete runnable example
Expected output
10 20
30 40
50 60
70 80
How the loops work
iidentifies the current layer.jidentifies the current row within that layer.kidentifies the current element within that row.numbers[i][j][k]reads the current element.- The first
println()starts a new line after each row. - The second
println()adds a blank line between layers.
Notice the loop conditions: each loop uses the length of the array at its own level. This is important when arrays have different row lengths.
8. Understanding the Three Indexes
Consider:
Each index has a distinct role:
For example, numbers[1][0][1] means:
1: the second layer0: the first row in that layer1: the second element in that row
In the sample array, numbers[1][0][1] is 60.
9. 3D Arrays with Different Row Sizes
Java multidimensional arrays are arrays of arrays. Their rows do not have to be the same length.
For example:
The first layer has rows of lengths 2 and 1. The second layer has rows of lengths 3 and 2.
To traverse this structure safely, use:
numbers.lengthfor the number of layers.numbers[i].lengthfor the number of rows in layeri.numbers[i][j].lengthfor the number of elements in rowjof layeri.
Complete runnable example
Expected output
Layer 0:
10 20
30
Layer 1:
40 50 60
70 80
10. Correct Flowchart for Traversing a 3D Array
The flowchart below represents the same three-loop traversal used in the Java example. It checks each level before entering it, prints each element, advances the column index first, then the row index, and finally the layer index.
Flowchart walkthrough
- Start with layer index
i = 0. - If
iis outside the layer count, stop. - Set row index
j = 0for the current layer. - If
jis outside that layer's row count, incrementiand move to the next layer. - Otherwise, set column index
k = 0for the current row. - Print each element while
kis less than that row's length, incrementingkafter each element. - When the row is finished, print a newline and increment
j. - Repeat until all rows and layers have been processed.
Why this flowchart is correct: the column loop completes before the row index advances, and the row loop completes before the layer index advances. Each boundary check uses the correct array level, so the logic also supports rows of different lengths, provided the nested arrays being accessed are non-null.
11. Common Mistakes
Mistake 1: Using only two indexes
Incorrect for a 3D array:
This refers to a row array, not an individual integer element. Use three indexes to access one integer:
Mistake 2: Mixing up the index order
The order is always layer, row, column. numbers[1][0][1] means layer 1, row 0, column 1—not layer 1, row 1, column 0.
Mistake 3: Using the wrong length
Use the length that matches the current level:
| Purpose | Correct expression |
|---|---|
| Visit all layers | numbers.length |
Visit rows in layer i | numbers[i].length |
Visit elements in row j of layer i | numbers[i][j].length |
Mistake 4: Assuming all rows have the same length
A 3D array can contain rows of different lengths. Avoid hard-coding one column count for every row unless the structure is guaranteed to be rectangular.
Mistake 5: Going beyond valid indexes
Accessing an index outside the valid range causes an ArrayIndexOutOfBoundsException. For example, if there are two layers, valid layer indexes are 0 and 1.
Mistake 6: Forgetting to increment a loop index
If i, j, or k is not incremented appropriately, a loop may never end. Check that each loop advances its own index.
12. Time and Space Complexity
For a regular 3D array with L layers, R rows per layer, and C columns per row:
| Operation | Time complexity | Explanation |
|---|---|---|
| Access one element | O(1) | Three index lookups select the element |
| Update one element | O(1) | One assignment changes the selected value |
| Traverse all elements | O(L × R × C) | Every element is visited once |
| Store the elements | O(L × R × C) | The array contains that many values |
For a structure with different row lengths, let N be the total number of values. Traversing all layers and rows takes O(L + Q + N), where Q is the total number of row arrays and N is the total number of elements.
13. Best Practices
- Use meaningful names such as
numbers,temperatures, orcube. - Remember the index order: layer, row, column.
- Use the correct
lengthexpression for each level. - Prefer three nested loops when you need indexes or want to update values.
- Keep indentation consistent to make nested loops easier to read.
- Do not assume rows all have equal lengths unless your program guarantees it.
- Validate dimensions before creating arrays from user input.
- Check for
nullnested arrays if your program may assignnullto a layer or row. - For Java learning platforms, keep runnable examples in the required
public class Mainformat.
14. Practice Questions with Answers
Question 1: What is a 3D array?
Answer: A 3D array is an array structure accessed using three indexes, commonly interpreted as layer, row, and column.
Question 2: How many elements are in new int[2][3][4]?
Answer: It contains 2 × 3 × 4 = 24 integer elements.
Question 3: What does numbers.length return?
Answer: It returns the number of layers in the outer array.
Question 4: What does numbers[i][j].length return?
Answer: It returns the number of elements in row j of layer i, provided that row exists and is not null.
Question 5: What is the value of numbers[1][1][1] in the following array?
Answer: 80.
Question 6: Why are three nested loops commonly used?
Answer: The outer loop visits layers, the middle loop visits rows, and the inner loop visits values within each row.
Question 7: Write a program to calculate the sum of all elements.
Answer:
Expected output
Sum = 3615. Frequently Asked Questions (FAQs)
1. What is a 3D array in Java?
It is an array of arrays of arrays, commonly used to organize values by layer, row, and column.
2. How do you declare a 3D array?
Use three pairs of brackets, such as int[][][] numbers;.
3. How do you create a 3D array with 2 layers, 3 rows, and 4 columns?
Use int[][][] numbers = new int[2][3][4];.
4. How do you access one element?
Use numbers[layer][row][column].
5. Why does indexing start at zero?
Java arrays use zero-based indexing, so the first valid index at each level is 0.
6. Can a 3D array have rows with different lengths?
Yes. Java's multidimensional arrays are arrays of arrays, so different rows can have different lengths.
7. What is the time complexity of traversing a regular 3D array?
For L layers, R rows per layer, and C columns per row, traversal takes O(L × R × C) time.
8. What exception occurs when an invalid index is used?
An out-of-range index causes an ArrayIndexOutOfBoundsException.
16. Quick Revision
- A 3D array uses three indexes.
- Think of it as layers containing rows and columns.
- Declare it with
dataType[][][] arrayName. - Create it with
new dataType[layers][rows][columns]for a regular structure. - Access an element using
arrayName[layer][row][column]. numbers.lengthgives the number of layers.numbers[i].lengthgives the number of rows in layeri.numbers[i][j].lengthgives the number of values in rowjof layeri.- Three nested loops are commonly used to traverse every element.
- Java supports arrays whose rows have different lengths.
- Traversing a regular 3D array takes
O(L × R × C)time.
17. Conclusion
A three-dimensional array helps organize data across layers, rows, and columns. The most important skills are understanding the three indexes, initializing and updating values, and using three nested loops with the correct length expression at each level. Remember that Java multidimensional arrays are arrays of arrays, so individual rows can have different lengths. Practice the examples and follow the flowchart to build confidence with 3D arrays in Java.