Array = collection of same type data stored together
int r1 = 1001;
int r2 = 1002;
int r3 = 1003;int[] rollNumbers = new int[3];✔ One variable ✔ Stores multiple values ✔ Clean & scalable
- Array stores values in continuous memory
- Each value has an index (position)
- Index starts from 0
📌 From lecture: arrays store elements in contiguous memory locations
int[] arr;arr = new int[3];int[] arr = new int[3];int→ type[]→ array3→ size
| Index | Value |
|---|---|
| 0 | First |
| 1 | Second |
| 2 | Third |
int[] arr = new int[3];
arr[0] = 1001;
arr[1] = 1002;
arr[2] = 1003;System.out.println(arr[0]); // 1001
System.out.println(arr[1]); // 1002
System.out.println(arr[2]); // 1003System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[2]);for (int i = 0; i < 3; i++) {
System.out.println(arr[i]);
}for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}- Avoid hardcoding
- Works for any size
int[] arr = new int[3];
int x = 1001;
for (int i = 0; i < arr.length; i++) {
arr[i] = x;
x++;
}✔ Efficient ✔ No manual work
System.out.println(arr[3]); // ErrorArrayIndexOutOfBoundsException
📌 Happens when index ≥ size
System.out.println(arr.length);✔ Returns size of array
int[] arr = new int[3];👉 Looks like:
[10, 20, 30]
Array of Arrays
| Sub1 | Sub2 | Sub3 | |
|---|---|---|---|
| S1 | 50 | 30 | 90 |
| S2 | 60 | 40 | 80 |
| S3 | 70 | 50 | 70 |
int[][] marks = new int[3][3];marks[0][0] = 50;
marks[0][1] = 30;
marks[0][2] = 90;System.out.println(marks[1][2]); // 80for (int i = 0; i < marks.length; i++) {
for (int j = 0; j < marks[i].length; j++) {
System.out.print(marks[i][j] + " ");
}
System.out.println();
}i→ rowsj→ columns
| Feature | 1D | 2D |
|---|---|---|
| Structure | Line | Table |
| Index | 1 | 2 |
| Use | Simple list | Matrix / grid |
- Array = collection of same type
- Index starts from 0
- Stored in continuous memory
- Use
.lengthinstead of hardcoding - Use loops for efficiency
- 2D array = array of arrays
- Array = container with slots
- Index = address of slot
- Loop = automatic filling / reading