Types of Arrays
1. What Is an Array? (beginner)
Array = fixed-size row of same-type boxes, numbered from 0. Like 5 lockers in a line. Once sized (new int[5]), cannot grow (use ArrayList for growable!).
2. Three Types (exam list)
int[] a1 = {10, 20, 30}; // 1-D: single row
int[][] m = {{1,2},{3,4}}; // 2-D: table (rows × cols)
int[][] jag = new int[2][]; // jagged: rows differ!
jag[0] = new int[2]; jag[1] = new int[5]; // row0 len2, row1 len5
| Type | Shape | Access |
|---|---|---|
| 1-D | line | a[i] |
| 2-D (rect) | table | m[r][c] |
| Jagged | ragged rows | jag[r].length differs! |
3. Beginner Code — Marks Average
int[] marks = new int[3];
marks[0] = 80; marks[1] = 90; marks[2] = 70;
int sum = 0;
for (int i = 0; i < marks.length; i++) sum += marks[i]; // .length (no brackets!)
System.out.println(sum / (double) marks.length); // 80.0
4. Traps
- Index 0 to length-1:
marks[3]on len-3 →ArrayIndexOutOfBoundsException! new int[3]fills 0;new String[3]fills null.- Array has
.length(field, no()); String has.length()(method!).
5. Exam Points
- Declare + 2-D + jagged with diagram — 5-7 marks, very frequent.
- Average/largest program +
.length— 5 marks, frequent.