Foundation
07 — Arrays
Previous: 06 Methods · Next: 08 Strings
▶️ java pkg1core/core8ArraysDemo.java
Declaring arrays
1int[] a = {5, 3, 8, 1, 9}; // inline init2int[] b = new int[3]; // default: all zeros3b[0] = 10;- Fixed size once created
- Zero-indexed: first element is
[0] arr.lengthis a field (not a method)
2D arrays (matrix)
1int[][] grid = {2 {1, 2, 3},3 {4, 5, 6}4};5System.out.println(grid[1][2]); // 6An array of arrays — rows can differ in length (jagged).
java.util.Arrays utilities
1Arrays.sort(sorted);2Arrays.binarySearch(sorted, 8); // must be sorted first3Arrays.fill(arr, 7);4Arrays.copyOf(arr, 3);5Arrays.toString(arr);Common patterns
1// Reverse in place2for (int i = 0, j = a.length - 1; i < j; i++, j--) {3 int t = a[i]; a[i] = a[j]; a[j] = t;4}5 6// Sum7int sum = 0;8for (int v : a) sum += v;Arrays vs ArrayList
| Array | ArrayList | |
|---|---|---|
| Size | Fixed | Grows dynamically |
| Primitives | Yes (int[]) |
No (must box) |
| Performance | Faster, less memory | More flexible |
💡 Use arrays for fixed-size, performance-critical code; ArrayList for most application logic.
▶️ Dynamic array implementation: java pkg3datastructures/datastructures0DynamicArray.java
Next → 08 Strings Related → 01 Core Java
Source named in this chapter
- core8ArraysDemopkg1core/core8ArraysDemo.java
- datastructures0DynamicArraypkg3datastructures/datastructures0DynamicArray.java