Java Notes
A two-dimensional array stores rows of values. Learn creation, traversal, matrix totals, and the difference between rectangular and jagged arrays.
A two-dimensional array is an array whose elements are arrays. It is commonly used to represent rows and columns, such as a marks sheet, seating plan, grid, or matrix.
Create a matrix
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
marks[0][1] means row 0, then column 1. It returns 81 in this example.
Traverse rows and columns
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Use marks[row].length rather than assuming every row has the same number of columns. This works for both rectangular and jagged arrays.
Calculate a matrix total
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
This uses nested enhanced for loops. The outer loop gives one row at a time; the inner loop gives every value from that row.
Rectangular versus jagged
| Shape | Example | Access rule |
|---|---|---|
| Rectangular | Every row has three values | Each row.length happens to be the same. |
| Jagged | One row has two values and another has four | Check the current row.length. |
Java does not require a two-dimensional array to be rectangular. A jagged array is covered in the next lesson.
What to remember
- A two-dimensional array is an array of arrays.
- The first index selects a row; the second selects a value in that row.
array.lengthis the row count, whilearray[row].lengthis the current row's size.- Nested loops are the normal way to visit every cell.
Continue the lesson path