Java Array Basics: Length, Bounds, Copies, and Resizing

Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.

published: reading time: 16 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.

Java Array Basics: Length, Bounds, Copies, and Resizing

Java arrays hold a fixed number of elements of one type. Their length is set when they are created, but the value used to allocate them can be computed at runtime.

When to use arrays

Use arrays when:

  • The required length is known when you allocate the array and will not change afterward
  • You are working with primitive types where boxing overhead is unacceptable
  • You need a simple, low-overhead container with O(1) random access

Do not use arrays when:

  • The size needs to grow or shrink dynamically
  • You frequently insert or delete elements in the middle
  • You want collection operations such as adding or removing elements

Declaration, initialization, and access

// Declaration
int[] scores;

// Initialization
scores = new int[5];          // Default-initialized: all zeros
int[] primes = {2, 3, 5, 7, 11};  // Length is inferred as 5

// Access
System.out.println(primes[0]);   // 2
primes[2] = 6;                  // Modify element
System.out.println(primes.length); // 5

The length property

An array’s length is available as the length field, not a method. The length stays fixed after allocation, but the allocation can use a value computed at runtime: int[] data = new int[requestedLength];.

Empty arrays, bounds checks, aliases, and copies

An empty array is valid and has length zero. Since it has no valid indices, check an index before access. Assigning an array variable to another variable creates an alias; Arrays.copyOf() creates a separate array.

import java.util.Arrays;

public class ArrayBasicsDemo {
    public static void main(String[] args) {
        int[] empty = new int[0];
        int index = 0;
        if (index >= 0 && index < empty.length) {
            empty[index] = 1;
        }
        System.out.println("empty length = " + empty.length);
        System.out.println("index 0 is in bounds = " + (index < empty.length));

        int requestedLength = args.length == 0 ? 3 : Integer.parseInt(args[0]);
        if (requestedLength < 1) {
            throw new IllegalArgumentException("length must be at least 1");
        }
        int[] values = new int[requestedLength];
        if (values.length > 2) {
            values[2] = 7;
        }

        int[] alias = values;
        int[] copy = Arrays.copyOf(values, values.length);
        alias[0] = 10;
        copy[0] = 99;

        System.out.println("values = " + Arrays.toString(values));
        System.out.println("alias = " + Arrays.toString(alias));
        System.out.println("copy = " + Arrays.toString(copy));
    }
}

Save this as ArrayBasicsDemo.java, then run javac ArrayBasicsDemo.java && java ArrayBasicsDemo. The default run reports an empty length of 0 and an out-of-bounds index, then prints [10, 0, 7] for both values and alias, and [99, 0, 7] for copy.

Conceptual array layout

graph LR
    A["values: int[] reference"] --> B["array object<br/>length: 3"]
    B --> C["index 0: 10"]
    B --> D["index 1: 20"]
    B --> E["index 2: 30"]

Failure scenarios

Scenario Cause Result
ArrayIndexOutOfBoundsException Accessing a negative index or one >= length The access throws an exception.
NullPointerException Array variable is null and you access it The access throws an exception.
Forgetting length Hardcoded loop bound differs from array length Elements may be skipped or an exception may be thrown.
Uninitialized array reference A local variable is used before assignment Compile-time error; an uninitialized field defaults to null

Trade-off table

Aspect Arrays ArrayList / List
Primitive values int[] stores primitives directly ArrayList<Integer> stores wrapper objects
Type safety Same type only Generics provide compile-time checks
Flexibility Fixed size Dynamic resize
Size awareness .length field .size() method
Multi-dimensional Easy: int[][] Nested lists or third-party libs

Code snippets

Iterating an array

Java has two ways to loop over an array: the old-school index for loop and the enhanced for-each from Java 5. Which one you pick changes what you can do inside the loop and how much code you are on the hook for.

The standard for loop puts the index in your hands. You decide where it starts, stops, and how it increments. This pays off when you need the position — updating parallel arrays, finding where a match landed, anything that leans on location. The cost is verbosity and a whole class of off-by-one mistakes.

int[] values = {5, 10, 15, 20};

// Standard for loop
for (int i = 0; i < values.length; i++) {
    System.out.println(values[i]);
}

// Enhanced for-each loop
for (int val : values) {
    System.out.println(val);
}

The enhanced for-each drops the index entirely. The loop variable gives you the element value directly, not its position. That cuts out index mistakes and keeps the code short. Use it when you only need to read elements and do not need the position. Watch out though: assigning to the loop variable changes a local copy, not the array itself.

Scenario Loop type
Need the index for calculations Standard for loop
Need to modify array elements Standard for loop
Searching for a position Standard for loop
Simple read-only pass Enhanced for-each loop
Updating objects via setter Enhanced for-each loop

In tight loops over large primitive arrays, the standard version sometimes lets the JIT inline better since it has direct index access. For most code this does not matter. The enhanced loop is easier to read and that matters more in practice.

Copying and resizing

Java arrays cannot grow or shrink after creation. To change the length, allocate a new array and copy the elements you want to keep. If the size changes frequently, use an ArrayList instead.

System.arraycopy() copies a selected range into an existing destination array. It also handles overlapping source and destination ranges.

int[] original = {1, 2, 3};
int[] expanded = new int[original.length * 2];
System.arraycopy(original, 0, expanded, 0, original.length);
// expanded = {1, 2, 3, 0, 0, 0}

Arrays.copyOf() allocates a new array and copies as many elements as fit. A longer copy gets default values in its extra slots; a shorter copy keeps only the leading elements.

int[] original = {1, 2, 3};
int[] resized = Arrays.copyOf(original, original.length * 2);
// resized = {1, 2, 3, 0, 0, 0}

clone() makes an exact-length shallow copy. For primitive arrays, elements are copied by value. For object arrays, the new array contains the same object references.

int[] original = {1, 2, 3};
int[] copy = original.clone();
// copy = {1, 2, 3}

Use Arrays.copyOf() for a new array with a chosen length, System.arraycopy() to copy a range into an existing array, and clone() for an exact-length shallow copy.

Debugging checklist

  • Verify array indices are within bounds before access
  • Log the array length when debugging size-related issues
  • Check for uninitialized array variables in code paths
  • Monitor for repeated ArrayIndexOutOfBoundsException in production logs
  • Use breakpoints to inspect array contents during development

Security notes

  • Never trust user input as array indices — always validate
  • Avoid storing sensitive data (passwords, keys) in arrays if possible; arrays can be explicitly wiped but not garbage collected efficiently
  • When serializing objects containing arrays, ensure no sensitive data leaks through toString() output

Common pitfalls

  1. Off-by-one errors: Remember indices run from 0 to length - 1, not 1 to length
  2. Array vs. ArrayList: Arrays have fixed length; use a list when you need collection operations or a changing size.
  3. Anonymous array creation: new int[] {1, 2, 3} — the size is inferred, not specified
  4. Multidimensional confusion: new int[3][] creates an outer array with three null row references; allocate each row before accessing its elements.

Quick recap checklist

  • Allocate the array at the required runtime length; the length cannot change afterward.
  • Check indices against 0 <= index < array.length before access.
  • Remember that alias = array points to the same array; use Arrays.copyOf() for a separate array.
  • Use an ArrayList when the collection needs to grow or shrink.

Interview questions

1. What is the time complexity of accessing an element in an array by index, and why?

Model Answer: "In algorithm analysis, indexed access is O(1): the runtime checks the index and retrieves that element without searching through earlier elements. Java does not specify a physical memory layout for arrays, so contiguous-memory explanations describe a common implementation model, not a language guarantee."

2. What happens when you try to access an array element at a negative index?

Model Answer: "An access with a negative index throws `ArrayIndexOutOfBoundsException` at runtime. Java checks array bounds; a negative index does not wrap around."

3. What is the difference between `arr.length` and `arr.length()` in Java?

Model Answer: "`arr.length` is the array's `length` field; arrays do not have a `length()` method. `String` uses `length()`, while collections such as `List` use `size()`."

4. Can you store primitive types directly in an `Object[]` array, and what happens?

Model Answer: "No — an `Object[]` can only hold references to objects, not primitives. Primitives are automatically boxed to their wrapper types when stored in `Object[]`. For example, `new Object[]{ 42 }` stores an `Integer`, not an `int`. Accessing the element returns a reference to the boxed `Integer`, which must then be unboxed if you need the primitive value. This boxing/unboxing has performance cost and should be avoided in tight loops."

5. What is the default initialization values for elements of a newly created primitive array?

Model Answer: "All elements of a newly created primitive array are default-initialized: `byte`, `short`, `int`, and `long` default to `0`; `float` and `double` to `0.0`; `char` to the null character (Unicode U+0000); and `boolean` to `false`. This applies to local and instance arrays created with `new`. Local primitive variables that are not arrays must be initialized before use."

6. What is the difference between `int[] arr = new int[3]` and `int[] arr = {1, 2, 3}`?

Model Answer: "`new int[3]` creates a three-element array initialized with zeros. `{1, 2, 3}` is an array initializer that supplies the element values and implies a length of three. The initializer can be used at a declaration; `new int[] {1, 2, 3}` can also create the array in an expression."

7. Why is `Arrays.copyOf()` preferred over manually copying array contents in a loop?

Model Answer: "`Arrays.copyOf()` is a concise way to create an array of a chosen length and copy as many source elements as fit. Its implementation may use optimized copying, but performance depends on the runtime and workload. Choose it for clarity; benchmark before making a performance claim."

8. What is a ragged array in Java and how do you create one?

Model Answer: "A ragged array (jagged array) is a two-dimensional array where each row has a different length — essentially an array of arrays. Create it with `int[][] ragged = new int[3][]` where each inner array is independently allocated: `ragged[0] = new int[2]; ragged[1] = new int[5]; ragged[2] = new int[3];`. This differs from a rectangular array `int[3][5]` where all rows have exactly 5 columns. Ragged arrays are useful for representing triangular matrices, sparse structures, or variable-length records."

9. What causes `ArrayIndexOutOfBoundsException` and how do you prevent it?

Model Answer: "It is thrown when an index is negative or at least the array's length. Use `arr.length` for loop bounds, check user-provided indices with `index >= 0 && index < arr.length`, or choose an enhanced for-each loop when you do not need the index."

10. What is the relationship between arrays and the `Cloneable` interface in Java?

Model Answer: "All array types implement `Cloneable` and the `clone()` method produces a shallow copy — a new array with the same elements copied by reference for object types or copied by value for primitives. For a primitive array, `clone()` produces a completely independent copy. For an `Object[]` containing references, the new array holds the same references pointing to the same objects — modifying the objects through one array is visible through the other. Use `Arrays.copyOf()` for explicit control or deep clone logic for nested object contents."

11. What is the maximum size of an array in Java and what determines it?

Model Answer: "Array length is represented by an `int`, but the Java language does not promise that every nonnegative `int` is a usable array length. A JVM may impose a smaller implementation limit, and available memory also matters. Large allocations can fail with `OutOfMemoryError`; the practical limit depends on the JVM and machine."

12. How does `System.arraycopy()` behave when the source and destination ranges overlap?

Model Answer: "Overlapping source and destination ranges are supported. The result is as if the source elements were first copied to a temporary array, so an in-place shift such as `System.arraycopy(arr, 3, arr, 4, 5)` does not overwrite values before they are copied. Invalid ranges throw `IndexOutOfBoundsException`; incompatible reference-array elements can cause `ArrayStoreException`."

13. What is the advantage of using `java.nio.ByteBuffer` over a byte array for IO operations?

Model Answer: "`ByteBuffer` tracks position, limit, and mark, and supports operations such as `flip()`, `compact()`, and typed reads and writes. `allocateDirect()` requests storage outside the usual Java heap; some native I/O paths may benefit from it, but direct buffers do not guarantee zero-copy or faster performance. Choose one when its buffer operations or measured I/O behavior suit the workload."

14. Why does array declaration with varargs `void method(String... args)` create ambiguity with overloading?

Model Answer: "A varargs parameter `String... args` is represented as a `String[]` parameter, and the compiler also allows calls that supply its elements individually. With overloads `method(Object)` and `method(String...)`, `method(null)` can match the array parameter and may produce a varargs warning; it does not mean a single `String` argument is ambiguous. Cast to `String[]` when you mean the whole array, or use an overload design that makes the intended call clear."

15. What is the difference between a one-dimensional and two-dimensional array in memory layout?

Model Answer: "A two-dimensional Java array is an array whose elements are references to other arrays. For `new int[3][4]`, the outer array has three elements and each refers to a four-element `int[]`; the rows can also have different lengths. Java specifies this array-of-arrays structure, but it does not specify physical placement of the arrays in memory."

16. What is the effect of `final` on an array reference?

Model Answer: "`final int[] arr = new int[5]` makes the `arr` reference immutable — `arr` cannot be reassigned to a different array after declaration. However, the contents of the array are mutable — `arr[0] = 42` is perfectly legal and modifies the element. This is the distinction between reference immutability (`final`) and data immutability (immutable array). To make the contents immutable, you would need an immutable wrapper like `Collections.unmodifiableList()` or use Java 16+ `List.of()` with array conversion, though these create new collection objects rather than protecting the array itself."

17. What is the difference between `Arrays.stream(arr)` and `arr.length` for iteration?

Model Answer: "`Arrays.stream(arr)` creates a `Stream` from the array — useful for functional-style pipeline operations (`filter`, `map`, `collect`). `arr.length` is a property used in traditional index-based iteration (`for i = 0; i < arr.length; i++`). The stream API provides cleaner, more declarative code for transformations and aggregations, but a simple indexed loop or enhanced for-each loop (`for (int x : arr)`) has lower overhead and is often clearer for straightforward iteration. Streams add allocation overhead for the stream object itself."

18. Can you resize an array after creation, and what are your options if you need to?

Model Answer: "An array's length cannot change after it is created. You can allocate a new array and copy elements with `Arrays.copyOf()`, or use `ArrayList` when a collection needs to grow. The `ArrayList` API does not promise a particular capacity growth formula; giving it a useful initial-capacity estimate may reduce reallocations."

19. What is the purpose of `Arrays.equals()` and how does it differ from `Object.equals()` for arrays?

Model Answer: "`Object.equals()` compares object references, not contents — two arrays with identical contents but different object references are not equal via `Object.equals()`. `Arrays.equals()` compares array contents element-by-element using each element's `equals()` method. For example, `int[] a = {1,2}; int[] b = {1,2}; Arrays.equals(a, b)` returns `true`. For multi-dimensional arrays, use `Arrays.deepEquals()` which handles nested arrays. When implementing `equals()` for a class containing an array field, use `Arrays.equals()` to compare the array contents rather than relying on the inherited `Object.equals()` reference comparison."

20. What is the effect of autoboxing when storing primitive values in Object array slots?

Model Answer: "Assigning a primitive such as `42` to an `Object[]` boxes it as an `Integer`, because array elements must be references. Reading it back as an `int` unboxes it. Boxing may add allocation and garbage-collection costs, though the runtime can optimize some cases. If primitive storage matters, use a primitive array such as `int[]` or evaluate a suitable primitive collection."

Further reading

Summary

Arrays have a fixed length, and indexing takes constant time. Java checks each index at runtime. To change the number of elements, create another array or use a collection that supports resizing.

For a resizable collection, continue with ArrayList. It provides indexed access and lets you add or remove elements through the collection API.

For arrays of arrays, see Multidimensional Arrays.

Category

Related Posts

Abstract Classes in Java: Interfaces and Composition

Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.

#java-abstract-classes #java #java-fundamentals

Arithmetic Operators in Java: Division, Overflow, Promotion

Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.

#java-arithmetic-operators #java #java-fundamentals

ArrayList in Java

Compare ArrayList's Java SE 27 contract with OpenJDK 27 growth behavior, capacity hints, operation costs, fail-fast iterators, and bounded concurrency options.

#java-arraylist #java #java-fundamentals