Back to results for “Collections”
Java › Arrays & Multidimensional Arrays

How do you declare, initialize, and access elements of a one-dimensional array in Java?

Beginner

Answer

An array is declared with a type followed by square brackets (int[] arr), instantiated with new specifying its fixed size (new int[5]) or using an initializer literal ({1, 2, 3}), and accessed/modified via zero-based indexing (arr[0]) -- once created, an array's length is fixed and immutable for its lifetime, unlike a resizable collection like ArrayList.
int[] numbers = new int[5];  // all elements default to 0
numbers[0] = 10;
numbers[1] = 20;

int[] literal = {1, 2, 3, 4, 5};  // initializer syntax
System.out.println(literal[2]);  // prints 3
System.out.println(literal.length);  // prints 5, note: .length is a field, not a method
Real-world example A fixed-size lookup table mapping day-of-week integers (0-6) to day names is implemented as a simple String array, appropriate since the collection's size is known and fixed at compile time and never needs to grow or shrink.

Common follow-ups: Why is array.length a field access rather than a method call, unlike String's .length()?;What happens if you access an index outside the array's bounds?