Arrays
An array stores a fixed number of items of the same type, side by side in memory. Reading or writing by index is O(1). The size can't change after creation.
Arrays are the simplest and fastest data structure: items side by side with instant access by index. Many interview problems are array problems, solved with careful loops, two pointers or prefix sums.
Example
Reverse an array in place
Example
2-D arrays
Example
Prefix sums: fast range totals
Example
Reading
a[a.length] throws ArrayIndexOutOfBoundsException - valid indexes are 0 to length-1.Key points
- Fixed size; index access is O(1).
- Arrays.toString, sort and copyOf help.
- Prefix sums answer range totals in O(1).
📝 Test yourself
1. What's the time to read arr[i]?
2. What is the last valid index of an array of length 5?
3. Fill in the method that prints an array nicely:
System.out.println(Arrays.(a));
