Array

An array stores elements in contiguous memory and provides constant-time indexed access. In Java, arrays have a fixed length and hold values of one declared component type.

An array is an indexed collection whose elements occupy a fixed-size sequence. Java arrays use zero-based indexes, so an array of length `n` has valid indexes from `0` through `n - 1`.

Because the runtime can calculate an element's location from its index, reading or writing an element by index takes constant time, `O(1)`. This direct access is one of the main advantages of arrays over structures that require traversal.

Java arrays have a fixed length after creation. You can replace an element, but you cannot change the array's capacity; to hold more elements, you normally create another array or use a resizable collection such as `ArrayList`.

Java provides arrays for both primitives and references. For example, `int[]` stores integer values directly, while `String[]` stores references to `String` objects. Arrays are objects in Java, and their length is available through the `length` field.

Key points

Interview questions

What is an array, and why is indexed access `O(1)`?

An array stores elements in a fixed sequence of indexed positions. The runtime can compute the location of an element from its starting address and index, so it does not need to inspect preceding elements. Therefore, accessing an element by index is constant time, `O(1)`. This assumes ordinary direct array indexing rather than an operation that first searches for a value.

Can you change the length of a Java array after creating it?

No. A Java array has a fixed length established when it is created. You can modify the values stored in its existing positions, but you cannot increase or decrease its capacity. If a different capacity is needed, you create another array or use a resizable collection such as `ArrayList`.

What is the difference between `array.length` and `ArrayList.size()`?

For a Java array, `length` is a field containing the array's fixed number of slots. For an `ArrayList`, `size()` is a method that reports how many elements the list currently contains. An `ArrayList` can change its size as elements are added or removed, while an array cannot change length after construction. Both values are useful, but they describe different collection types.

What is the time complexity of inserting an element into the middle of an array?

If insertion means preserving the existing order and making room for a new element, elements after the insertion point must be shifted. In the worst case, that can move a number of elements proportional to the array length, giving `O(n)` time. A fixed Java array also cannot increase its length, so inserting while preserving capacity may require a new array. If overwriting an existing position is what is meant by insertion, that operation is `O(1)`.