1D Array Reference
| Operation |
Syntax |
Notes |
| Declare + create |
int[] arr = new int[5]; |
Fixed size, defaults to 0 |
| Declare + initialize |
int[] arr = {1, 2, 3}; |
Size = number of values |
| Access element |
arr[i] |
0-indexed |
| Set element |
arr[i] = value; |
Direct assignment |
| Length |
arr.length |
Field (no parentheses) |
| Last element |
arr[arr.length - 1] |
Common exam question |
| Standard for loop |
for (int i = 0; i < arr.length; i++) |
Use when modifying or need index |
| Enhanced for loop |
for (int val : arr) |
Read-only, no index access |
| Default: int[] |
0 |
Primitives default to zero-value |
| Default: String[] |
null |
Objects default to null |
ArrayList Reference
| Method |
Syntax |
Notes |
| Create |
ArrayList list = new ArrayList(); |
Must use wrapper class for primitives |
| Size |
list.size() |
Method with parentheses |
| Add to end |
list.add(element) |
Returns true, grows list by 1 |
| Add at index |
list.add(index, element) |
Shifts elements right |
| Get element |
list.get(index) |
Returns element at index |
| Set element |
list.set(index, element) |
Replaces in place, returns old value |
| Remove by index |
list.remove(index) |
Shifts elements left, returns removed |
| Standard for |
for (int i = 0; i < list.size(); i++) |
Use when modifying or removing |
| Enhanced for |
for (Type val : list) |
Cannot add/remove during iteration |
Critical Differences (Exam Traps)
| Feature |
Array |
ArrayList |
| Size syntax |
.length |
.size() |
| Access syntax |
arr[i] |
list.get(i) |
| Can resize? |
No |
Yes |
| Primitives? |
Yes |
No (use Integer, Double) |
| Modify in for-each? |
No effect |
ConcurrentModificationException |
2D Array Reference
| Operation |
Syntax |
Notes |
| Declare + create |
int[][] grid = new int[rows][cols]; |
rows × cols grid |
| Number of rows |
grid.length |
Outer array length |
| Number of columns |
grid[0].length |
Inner array length |
| Access element |
grid[row][col] |
Row first, column second |
| Row-major traversal |
for r < grid.length, for c < grid[0].length |
Outer=rows, inner=cols |
| Column-major traversal |
for c < grid[0].length, for r < grid.length |
Outer=cols, inner=rows |