Arrays in Java
An array is a fixed-size, ordered collection of elements, all of the same type, stored in contiguous memory locations. Arrays are the most fundamental data...
Storing and Accessing Collections of Data with Arrays
An array is a fixed-size, ordered collection of elements, all of the same type, stored in contiguous memory locations. Arrays are the most fundamental data structure in Java and are the basis for many higher-level structures. Understanding how to declare, create, initialize, and iterate arrays is essential for virtually every Java programming task.
Declaring an array variable specifies the element type followed by square brackets: int[] scores;. The brackets can also follow the variable name (int scores[]) but the former style is preferred in Java. This declaration does not create the array; it only declares a reference variable that can point to an array. Creating the array uses the new keyword: scores = new int[5];. This allocates memory for five integers, all initialized to 0. The two steps are usually combined: int[] scores = new int[5];.
You can also initialize an array with specific values using an array initializer: int[] primes = {2, 3, 5, 7, 11};. The size is inferred from the number of elements. Array elements are accessed using a zero-based index: primes[0] is 2, primes[4] is 11. Accessing an index outside the valid range (0 to length-1) throws an ArrayIndexOutOfBoundsException at runtime.
The length of an array is stored in its public final field: primes.length returns 5. Note that length is a field, not a method — there are no parentheses. Contrast this with String's length() method which does have parentheses.
Arrays are objects in Java. Declaring int[] arr means arr is a reference to an array object on the heap. When you assign one array variable to another (int[] b = a;), both variables point to the same array; modifying b[0] also changes a[0]. To get an independent copy, use Arrays.copyOf(a, a.length) from the java.util.Arrays class.
The java.util.Arrays class provides many useful methods: Arrays.sort(arr) sorts the array in place using a dual-pivot quicksort for primitives. Arrays.binarySearch(arr, key) searches a sorted array in O(log n) time. Arrays.fill(arr, value) fills every element with the given value. Arrays.toString(arr) returns a string representation like "[2, 3, 5, 7, 11]" for printing.
Interview tip: Array declaration, creation, and index errors are frequent in coding tests. Always check: is the array null? Is the index within bounds? Remember that the last valid index is array.length - 1, not array.length. Off-by-one errors at array boundaries are among the most common bugs in beginner and even experienced developer code.