← Learning Hub
Beginner

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
You can edit this code.

Reverse an array in place

Example
You can edit this code.

2-D arrays

Example
You can edit this code.

Prefix sums: fast range totals

Example
You can edit this code.
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));