Language Fundamentals

Arrays

Arrays are fixed-length, zero-indexed containers of a single type, with fast index access and bounds checking. They are covariant (dangerously so) and low-level — collections are usually the better default.
  • Length is fixed at creation; elements get default values (0, false, null)
  • Out-of-bounds access throws ArrayIndexOutOfBoundsException — no silent corruption
  • Arrays are covariant: String[] is a Object[] — wrong writes fail only at runtime
  • Arrays utility: sort, binarySearch, copyOf, fill, equals, toString, stream
  • Multidimensional arrays are arrays of arrays — rows can be jagged
  • Prefer List in APIs (EJ 28); use arrays at hot spots and for primitives
Creating arrays
int[] counts = new int[100];                 // all zero
String[] sizes = { "S", "M", "L", "XL" };    // initializer
int[][] magic = {
    { 16, 3, 2, 13 },
    { 5, 10, 11, 8 },
};
int[] copy = Arrays.copyOf(counts, counts.length * 2); // grow via copy

An array variable is a reference; assignment aliases the same data. Copy with Arrays.copyOf/copyOfRange or System.arraycopy. array.length (a field, not a method) gives the size; iterate with for-each or Arrays.stream(a).

Arrays.sort uses dual-pivot quicksort for primitives and TimSort (stable) for objects. binarySearch requires a sorted array. Arrays.equals/Arrays.deepEquals compare contents — == and equals() on arrays compare references only, and toString() prints gibberish like [I@1b6d3586; use Arrays.toString.

Performance-wise, primitive arrays are the densest data layout Java offers — contiguous, no per-element object headers, cache-friendly. That is why they remain the tool of choice in hot numeric code (see Language Performance and Hardware Memory).

Sources
  • Core Java, Volume I: Fundamentals (13th ed.)Ch. 3.10 — Arrays
  • Learning Java (6th ed.)Ch. 4 — The Java Language (Arrays)
  • Effective Java (3rd ed.)Item 28