Skip to content
Preview · sample content · Explore all pages

Java arrays and bounds

Last updated: 28 Sept 20263 min read
tutorial
By AITrove Editorial

An array is a fixed-length, indexed container whose elements share a component type.

Working model

Allocate the array when its length is known. Indexing is O(1), but valid indices stop at length - 1. An array with length zero is valid and has no readable element.

Code

Java
int[] dailyOrders = {12, 0, 8, 15};
int totalOrders = 0;
for (int orders : dailyOrders) {
    totalOrders += orders;
}
System.out.println(totalOrders);

The output is 35. Summation visits every element: O(n) time and O(1) extra space. A larger input may overflow an int total, so select the accumulator type from the expected range.

Cost and design choices

An array reference can be shared. Passing dailyOrders into a method does not create a separate array. Copy it when a caller must keep an unchanged snapshot.

Aliasing, covariance, and copying

Arrays.copyOf creates another array but only copies references for object elements. If an element is mutable, both arrays still reach that element. A two-dimensional Java array is an array of row references, so copying the outer array also shares the original rows.

A reference array can be assigned to a wider reference-array type. Its actual component type still controls writes, so storing an incompatible element throws ArrayStoreException. Generic lists use a different invariance rule that catches many such assignments at compilation.

Connected lessons

Continue with Java strings and content equality, Java Tutorial.

Common Mistakes

Do not assume every row of a two-dimensional array has the same length. Validate an index before accessing it. An array of object references initially contains null unless each element is assigned.

java
arrays
Storage details