Language Fundamentals
Arrays
- 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 aObject[]— wrong writes fail only at runtime Arraysutility:sort,binarySearch,copyOf,fill,equals,toString,stream- Multidimensional arrays are arrays of arrays — rows can be jagged
- Prefer
Listin APIs (EJ 28); use arrays at hot spots and for primitives
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 copyAn 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).