1. Introduction to a Two-Dimensional Array
A two-dimensional array, commonly called a 2D array, stores data in rows and columns. It is useful when data naturally fits into a table, such as marks for multiple students across subjects, a game board, or values arranged in a grid.
Premium Video
This video is available to Premium members or users who have purchased the course.
Sign in to UnlockFor example, consider this array:
| Row / Column | Column 0 | Column 1 | Column 2 |
|---|---|---|---|
| Row 0 | 10 | 20 | 30 |
| Row 1 | 40 | 50 | 60 |
This array contains 2 rows and 3 columns, giving it 6 elements.
In Java, a 2D array is an array of arrays. Each row is itself an array, so rows can have different lengths. When all rows have the same number of elements, the array forms a regular rectangular table.
Learning objectives
After reading this article, you will be able to:
- Declare and create a 2D array in Java.
- Initialize an array with values.
- Understand row and column indexes.
- Access and update individual elements.
- Traverse a 2D array using nested loops.
- Read values into a 2D array using
Scanner. - Understand jagged arrays and their row lengths.
- Avoid common indexing errors and analyze basic time complexity.
2. Declaring and Creating a 2D Array
The general syntax is:
dataType[][] arrayName = new dataType[rows][columns];
dataTypespecifies the type of values, such asint,double, orString.arrayNameis the variable used to refer to the array.rowsspecifies how many row arrays are created.columnsspecifies the number of elements in each row in this rectangular form.
For example, int[][] numbers = new int[2][3]; creates an integer array with 2 rows and 3 columns. Because it is an int array, its elements initially contain 0.
Complete runnable example
Expected output
Number of rows: 2
Columns in row 0: 3
Default value: 0
How it works
new int[2][3]creates two row arrays, each with three integer elements.numbers.lengthreturns the number of rows.numbers[0].lengthreturns the number of elements in the first row.numbers[0][0]refers to the first element, which is0before any value is assigned.
3. Initializing a 2D Array
You can provide values directly using nested braces. This is called array initialization.
The first inner array becomes row 0, and the second inner array becomes row 1.
| Expression | Meaning | Value |
|---|---|---|
numbers[0][0] | First row, first column | 10 |
numbers[0][1] | First row, second column | 20 |
numbers[0][2] | First row, third column | 30 |
numbers[1][0] | Second row, first column | 40 |
numbers[1][1] | Second row, second column | 50 |
numbers[1][2] | Second row, third column | 60 |
Both row and column indexes start at 0, not 1.
Complete runnable example
Expected output
First row: 10 20 30
Second row: 40 50 60
4. Accessing Elements in a 2D Array
To access one element, use:
arrayName[rowIndex][columnIndex]
The first index selects the row. The second index selects an element within that row.
For example, in the array {{10, 20, 30}, {40, 50, 60}}:
numbers[0][0]is10.numbers[0][2]is30.numbers[1][0]is40.numbers[1][2]is60.
Complete runnable example
Expected output
1060
Explanation: numbers[0][0] accesses the first element of the first row. numbers[1][2] accesses the third element of the second row.
Remember
For an array with 2 rows and 3 columns, valid row indexes are 0 and 1, while valid column indexes are 0, 1, and 2.
5. Updating an Element
You can change a stored value by assigning a new value to a particular row and column.
For example:
numbers[0][1] = 100;
This updates the element at row 0, column 1. Its old value was 20, and its new value is 100.
Complete runnable example
Expected output
Updated value: 100
Updated first row:
10 100 30
Explanation: The assignment changes only the selected element. The other elements remain unchanged.
6. Traversing a 2D Array Using Nested Loops
Traversal means visiting the array elements one by one. Nested loops are commonly used for 2D arrays:
- The outer loop moves through the rows.
- The inner loop moves through the elements in the current row.
Complete runnable example
Expected output
10 20 3040 50 60
How the loops work
istarts at0, so the outer loop selects the first row.jruns from0tonumbers[i].length - 1, printing each element in that row.System.out.println()moves the output to a new line after a row is printed.- The outer loop advances to the next row and repeats the process.
Important expressions
| Expression | Meaning |
|---|---|
numbers.length | Number of rows |
numbers[i].length | Number of elements in row i |
numbers[i][j] | Element at row i, position j |
Using numbers[i].length in the inner loop is important because Java rows do not always have to be the same length.
7. Traversing a 2D Array with an Enhanced for Loop
Java's enhanced for loop can make traversal simpler when you only need to read each value and do not need the row or column indexes.
Complete runnable example
Expected output
10 20 30
40 50 60
Explanation
for (int[] row : numbers)visits each row array.for (int value : row)visits every value in the current row.- The enhanced loop is readable and works with rows of different lengths.
- Use traditional indexed loops when you need positions, want to update elements by index, or need to compare neighboring elements.
8. Taking 2D Array Input Using Scanner
You can read the number of rows and columns from the user and then fill the array with input values. The example below reads a rectangular integer array.
Complete runnable example
Sample input
2
3
10 20 30 40 50 60
Sample output
Enter number of rows: Enter number of columns: Enter 6 integers:The array is :10 20 3040 50 60
Explanation: The first two inputs specify the dimensions. The nested loops then read one integer into each cell. Finally, another pair of nested loops prints the values row by row.
Input validation note: This beginner example assumes the user enters valid, non-negative dimensions and enough integer values. Production programs should validate input before creating the array.
9. Understanding a Jagged Array
A Java 2D array is an array of arrays, so its rows can have different lengths. Such an array is called a jagged array.
Example:
| Row index | Values | Row length |
|---|---|---|
| 0 | 10, 20 | 2 |
| 1 | 30, 40, 50 | 3 |
| 2 | 60 | 1 |
Complete runnable example
Expected output
Row 0: 10 20
Row 1: 30 40 50
Row 2: 60
Why does numbers[i].length matter?
If you used the length of the first row for every row, the loop could miss elements in longer rows or try to access nonexistent positions in shorter rows. Using numbers[i].length checks the length of the current row and traverses it safely.
10. Visualizing Nested-Loop Traversal
The following flowchart shows the general process for printing every element in a rectangular 2D array.
Flowchart explanation:
- Start with the first row.
- Check whether the row index is within the array's row count.
- For that row, start at the first column.
- Print each element while the column index is within that row's length.
- Move to the next row after finishing the current row.
- Stop when every row has been processed.
11. Common Mistakes in 2D Arrays
Mistake 1: Starting indexes at 1
Incorrect:
numbers[1][1]
This is not the first element; it refers to the second row and second element, if those positions exist.
Correct first-element access:
numbers[0][0]
Mistake 2: Confusing rows and columns
numbers.lengthgives the number of rows.numbers[i].lengthgives the number of elements in rowi.
Do not use numbers[i].length as the row count.
Mistake 3: Using one row's length for every row
This can fail for jagged arrays.
Safer inner-loop condition:
j < numbers[i].length
Mistake 4: Going beyond an array's bounds
If an array has 2 rows, the valid row indexes are 0 and 1. Trying to access numbers[2] causes an ArrayIndexOutOfBoundsException.
Always ensure indexes are within valid bounds before accessing an element.
Mistake 5: Forgetting the newline after each row
If you omit System.out.println() after the inner loop, all values may appear on one line. Put the newline after the inner loop when you want a table-like display.
Mistake 6: Assuming every 2D array is rectangular
Java allows jagged arrays. Check each row's own length if the code must work for any 2D array.
12. Time and Space Complexity
For a rectangular array with R rows and C columns:
| Operation | Time complexity | Explanation |
|---|---|---|
| Access one element | O(1) | Two index lookups select the row and element |
| Update one element | O(1) | One assignment changes the selected element |
| Traverse all elements | O(R × C) | Every cell is visited once |
| Print all elements | O(R × C) | Each cell is processed once, excluding output-device overhead |
The array itself stores R × C elements, so its element storage is O(R × C).
For a jagged array with row lengths \(L_0, L_1, \ldots, L_{R-1}\), traversal takes O(R + N), where \(N\) is the total number of elements, \(N = \sum L_i\). The R term accounts for visiting the rows; for a non-empty array, this is often expressed as O(R + N).
13. Best Practices
- Use meaningful names such as
marks,matrix, orgrid. - Remember that row and column indexes start at
0. - Use
numbers.lengthfor the row count andnumbers[i].lengthfor the current row's length. - Prefer nested loops when row and column indexes are needed.
- Prefer enhanced
forloops when you only need to read every value. - Check dimensions and input before creating arrays from user-provided values.
- Keep indentation consistent so the outer and inner loops are easy to follow.
- Use jagged arrays only when rows genuinely need different lengths.
- Keep examples in the required Java runner format:
public class Mainandpublic static void main(String[] args).
14. Practice Questions with Answers
Question 1: What is a 2D array?
Answer: A 2D array stores values in rows and columns. In Java, it is an array whose elements are references to row arrays.
Question 2: How many elements are in int[][] a = new int[3][4];?
Answer: It has 3 rows and 4 columns, so it contains 3 × 4 = 12 integer elements.
Question 3: What does a[1][2] mean?
Answer: It accesses the element at row index 1 and column index 2—the second row and third element of that row.
Question 4: What does a.length return?
Answer: It returns the number of rows in the 2D array.
Question 5: What does a[0].length return?
Answer: It returns the number of elements in the first row, provided the first row exists and is not null.
Question 6: What is a jagged array?
Answer: A jagged array is a 2D array whose rows can have different lengths.
Question 7: What is printed by this code?
Answer:
3Question 8: Write a program to find the sum of all elements in a 2D array.
Answer:
Expected output
Sum = 21Explanation: The nested loops visit each element once and add it to sum.
15. Frequently Asked Questions (FAQs)
1. What is a 2D array in Java?
A 2D array is an array of arrays that is commonly used to represent data in rows and columns.
2. How do you declare a 2D array in Java?
Use dataType[][] arrayName, for example, int[][] numbers.
3. How do you create a 2D array with 3 rows and 4 columns?
Use int[][] numbers = new int[3][4];.
4. How do you access an element in a 2D array?
Use arrayName[rowIndex][columnIndex], such as numbers[1][2].
5. Why are nested loops used with 2D arrays?
The outer loop commonly visits each row, while the inner loop visits each element in that row.
6. What is the difference between numbers.length and numbers[i].length?
numbers.length gives the number of rows. numbers[i].length gives the number of elements in row i.
7. Can rows in a Java 2D array have different lengths?
Yes. Java supports jagged arrays, where each row may contain a different number of elements.
8. What happens if an invalid index is used?
Accessing an index outside the available range causes an ArrayIndexOutOfBoundsException.
9. What are the default values in a newly created integer 2D array?
Each element of a newly created int array is initialized to 0.
10. What is the time complexity of traversing a rectangular 2D array?
For R rows and C columns, traversal takes O(R × C) time because every element is visited once.
16. Quick Revision
- A 2D array organizes data into rows and columns.
- In Java, a 2D array is an array of arrays.
- Declare with
int[][] numbersand create withnew int[rows][columns]. - Use nested braces to initialize values directly.
- Use
numbers[row][column]to access or update an element. - Indexes start at
0. numbers.lengthgives the number of rows.numbers[i].lengthgives the length of rowi.- Nested loops are commonly used to traverse all elements.
- Enhanced
forloops provide a readable alternative when indexes are not needed. - A jagged array has rows of different lengths.
- Traversing a rectangular array takes
O(R × C)time.
17. Conclusion
A two-dimensional array is a useful Java data structure for representing information in rows and columns. To work with it confidently, understand how to declare and initialize the array, use row and column indexes, update elements, and traverse values with nested loops. Remember that Java 2D arrays are arrays of arrays, so individual rows can have different lengths. Practicing these fundamentals will prepare you for matrix operations, tabular data, and more advanced array problems.