Arrays in Java: Indexing, Traversal and Worked Examples

Build a reliable model of Java arrays, then trace mutation, traversal, copying, logical deletion and ragged rows with exact values.

KnowledgeGate Team

Exam prep & CS education

Updated 20 Nov 20266 min read
Arrays in Java: Indexing, Traversal and Worked Examples

Java array questions become difficult when one fixed-capacity object carries two sizes: physical length and logical element count. Indexed reads may be constant time while insertions and deletions still move several values.

Use Arrays in Java: Declaration, Traversal, 2D Arrays and Worked Examples for declaration syntax, java.util.Arrays utilities and a broad marks traversal. Sequential-data-structure reasoning begins with state changes: shift in the correct direction, track logical size, trace aliases through method calls, and distinguish a bad index from a null element.

Build the correct Java array model

An array is a fixed-length Java object whose numbered slots share one component type. Valid physical indices run from 0 to array.length - 1, and array.length is a field. A sequential structure backed by an array usually needs a separate size variable for the number of active elements.

java
int[] values = {14, 9, 21, 17, 0, 0};
int size = 4;

The physical length is 6, the logical size is 4, and the active indices are 0 through 3. Accessing values[4] is legal Java but reads a spare slot outside the active sequence; values[6] throws ArrayIndexOutOfBoundsException. New numeric slots default to 0, reference slots to null, and boolean slots to false.

Trace one-dimensional insertion and deletion step by step

Java array timeline showing insertion of 15 at index 2 and deletion of 9 at index 1.

Insert 15 at active index 2. Existing elements must shift right from the highest active index downward so that no source is overwritten:

java
int insertAt = 2;
for (int i = size; i > insertAt; i--) {
    values[i] = values[i - 1];
}
values[insertAt] = 15;
size++;

Now delete active index 1, whose value is 9. Elements shift left from the deletion point upward. After the shift, decrement size first, then clear the newly inactive slot:

java
int deleteAt = 1;
int removed = values[deleteAt];
for (int i = deleteAt; i < size - 1; i++) {
    values[i] = values[i + 1];
}
size--;
values[size] = 0;

Operation

Backing array after the operation

Active sequence

Start: size = 4

[14, 9, 21, 17, 0, 0]

[14, 9, 21, 17]

Copy index 3 to 4

[14, 9, 21, 17, 17, 0]

[14, 9, 21, 17]

Copy index 2 to 3

[14, 9, 21, 21, 17, 0]

[14, 9, 21, 21]

Write 15 at index 2; size = 5

[14, 9, 15, 21, 17, 0]

[14, 9, 15, 21, 17]

Shift left before size--

[14, 15, 21, 17, 17, 0]

[14, 15, 21, 17, 17]

Clear index 4; size = 4

[14, 15, 21, 17, 0, 0]

[14, 15, 21, 17]

Insertion moves two existing values, from indices 3 and 2. Deletion moves three values, originally at indices 2, 3 and 4. The final active sequence is [14, 15, 21, 17], while the allocated length remains 6.

Connect access, update, search and logical deletion to cost

Physical storage and operation cost are separate questions. Reading or updating a known valid index does not depend on the array length, but finding an unknown value and preserving order during insertion or deletion may inspect or move a suffix.

Operation

Time

Reason

Read or update a known index

O(1)

The index identifies one slot directly

Linear search

O(n)

The target may be absent or in the final active slot

Traverse all active elements

O(n)

Each active slot is visited once

Insert at active index p

O(n - p)

The suffix shifts right

Delete at active index p, preserving order

O(n - p - 1)

Later elements shift left

If order does not matter, deletion can overwrite the removed slot with the final active value and decrement size in constant time. That changes the sequence order, so it is not a substitute when order carries meaning. For resizable lists and other implementations built around these trade-offs, continue with DSA using Java.

Trace aliases, real copies and method calls

Assignment aliases one array object, while Arrays.copyOf allocates another top-level array. A method call makes the distinction visible:

java
static void mutateThenRebind(int[] x) {
    x[1] = 40;
    x = new int[] {7, 8};
    x[0] = 99;
}

int[] original = {10, 20, 30};
int[] alias = original;
int[] copy = Arrays.copyOf(original, original.length);
mutateThenRebind(original);

After the call, original and alias both observe [10, 40, 30], while copy remains [10, 20, 30]. The write of 40 reaches the shared original object before the local parameter is rebound. The later write of 99 reaches only the new local array. Java passes the reference value by value; for object arrays, Arrays.copyOf still copies references rather than cloning their objects.

Read two-dimensional and ragged arrays as arrays of arrays

Consider int[][] scores = {{8, 6, 7}, {5, 9, 4}};. Here, scores.length = 2, while scores[0].length = 3 and scores[1].length = 3. The access scores[1][2] returns 4. A nested loop visits values in row order, 8, 6, 7, 5, 9, 4. The row totals are 8 + 6 + 7 = 21 and 5 + 9 + 4 = 18, giving a grand total of 21 + 18 = 39.

The model matters: scores refers to an outer array whose two slots refer to separate row arrays. Java therefore permits ragged rows. For int[][] steps = {{2, 4}, {6, 8, 10}, {12}};, the row lengths are 2, 3 and 1. steps[1][2] is 10, but steps[2][1] is outside the one-element third row and fails at runtime.

Do not use the shortcut columns = scores.length. A row length comes from the chosen row. To handle arbitrary ragged data, the inner loop condition must be j < scores[i].length.

Array-of-arrays diagram: scores of length 2 points to rows 8, 6, 7 and 5, 9, 4, with row totals 21 and 18 and grand total 39.

Separate primitive slots from reference slots

Compare int[] counts = new int[3]; with String[] labels = new String[3];. The first array contains three primitive 0 values. The second contains three null references. After labels[0] = "red", slot 0 stores a reference to a created or reused String object, while slots 1 and 2 remain null.

That difference produces two distinct failures. labels[0].length() returns 3, but labels[1].length() throws NullPointerException because slot 1 contains no object reference to follow. In contrast, labels[3] throws ArrayIndexOutOfBoundsException because a length-three array has no fourth slot. One error concerns the value in a valid slot; the other concerns an invalid index. Read String Handling in Java: Pool, Immutability, Interview Questions for the deeper String object and reference model.

Fix shift and size traps that produce wrong outputs

Four direction and boundary checks catch the failures that are specific to an array-backed sequence:

Wrong step

Result

Repair

Shift an insertion suffix from low to high

A copied value overwrites the next source and cascades right

Shift from the highest active index down to the insertion point

Shift a deletion suffix from high to low

An overwritten value cascades left

Shift from the deletion point upward

Traverse to values.length after logical deletion

Spare or stale slots enter the result

Traverse while i < size

Insert when size == values.length

Writing values[size] is out of bounds

Check capacity or allocate a larger array before shifting

The preservation rule decides direction: insertion shifts right from high to low, while deletion shifts left from low to high. After either operation, 0 <= size && size <= values.length must remain true.

How questions test Java arrays, then the short version

Questions often ask for the exact backing array after each shift, the active sequence after logical deletion, the number of moved elements, alias effects, row bounds and default values. In the worked trace, insertion at index 2 moves two elements and deletion at index 1 from five active elements moves three. Direct access remains O(1), while an order-preserving insertion or deletion is linear in the shifted suffix.

Keep the model compact: length is physical and fixed; size is logical and changeable; active indices stop at size - 1; assignment aliases; Arrays.copyOf creates a new top-level array; and each ragged row owns its length. Study the sequence in the Java Course: Concepts, MCQs & Coding Questions, then rerun the insertion at index 0 and deletion at the final active index. Predict the backing array and exact assignment count before executing the code.