Declare and use one-dimensional and two-dimensional arrays
📚 One‑Dimensional Arrays
Think of a one‑dimensional array as a row of lockers.
Each locker can hold a single value, and you can access any locker by its number (called the index). In Java, array indices start at 0 – the first locker is 0, the second is 1, and so on.
Declaring an Array
You first tell Java the type of data the array will hold and how many elements it will contain.
int[] scores = new int[5]; // 5 lockers, all initially 0 String[] names = new String[3]; // 3 lockers for names
Accessing Elements
You can read or write a value by specifying its index:
scores[0] = 88; // First locker gets 88 int firstScore = scores[0]; // Read the first locker
Remember: scores[5] would be out of bounds because the last valid index is 4.
Looping Through an Array
Loops let you perform the same operation on every element. The for‑each loop is handy for reading:
for (int score : scores) {
System.out.println(score);
}
If you need the index (for example, to print “Locker 2: 88”), use a classic for loop:
for (int i = 0; i < scores.length; i++) {
System.out.println("Locker " + (i+1) + ": " + scores[i]);
}
🗂️ Two‑Dimensional Arrays
A two‑dimensional array is like a grid of lockers – rows and columns. Think of a chessboard or a spreadsheet.
Declaring a 2D Array
int[][] matrix = new int[3][4]; // 3 rows, 4 columns
You can also declare and initialise in one line:
int[][] grid = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9,10,11,12}
};
Accessing Elements
Use two indices: matrix[row][col] – the first number is the row, the second is the column.
int value = matrix[1][2]; // second row, third column matrix[0][0] = 99; // top‑left corner
Looping Through a 2D Array
Nested loops let you visit every cell:
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[r].length; c++) {
System.out.print(matrix[r][c] + " ");
}
System.out.println(); // new line after each row
}
Visualising a 2D Array
Below is a small 2×3 grid. The top row is matrix[0], the bottom row is matrix[1]:
| Row\Col | 0 | 1 | 2 |
|---|---|---|---|
| 0 | 5 | 3 | 8 |
| 1 | 2 | 7 | 1 |
Key Takeaways
- Arrays are zero‑based: the first element is at index
0. - Use
array.length(ormatrix.lengthfor rows) to find how many elements exist. - Two‑dimensional arrays are arrays of arrays –
matrix[row]returns a one‑dimensional array. - Loops are essential for iterating over arrays, especially when the size is not known at compile time.
- Visualising arrays as grids or shelves helps remember how indices map to positions.
Happy coding! 🚀
Revision
Log in to practice.