Arrays
An array is a fixed-size, ordered container that holds multiple values of the same type under a single variable name. Arrays are one of the most fundamental data structures in Java — once you understand them, almost every other collection type starts to make sense.
What Is an Array?
Think of an array as a row of numbered boxes. Each box holds one value, and every box in the row is the same type. You can jump to any box instantly by its index number (starting at 0).
int[] scores = {90, 85, 78, 92, 88};
System.out.println(scores[0]); // first element
System.out.println(scores[4]); // last element
Output:
90
88
Key properties of arrays in Java:
- Fixed size — once created, the length never changes
- Zero-indexed — first element is at index
0, last is atlength - 1 - Type-safe — all elements must be the same type
- Objects — arrays are objects on the heap, even for primitive types
Declaring and Creating Arrays
There are two steps: declare a variable that refers to an array, then create the array itself.
// Step 1: declare
int[] numbers;
// Step 2: create (allocate memory for 5 integers)
numbers = new int[5];
You can combine both steps on one line:
int[] numbers = new int[5]; // all elements default to 0
Default Values
When you create an array with new, Java fills every slot with a default value automatically:
| Element Type | Default Value |
|---|---|
int, long, short, byte | 0 |
double, float | 0.0 |
boolean | false |
char | '\u0000' (null char) |
| Object references | null |
Array Initializer Shorthand
When you already know the values, use an initializer list — no new keyword needed:
String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
double[] prices = {9.99, 19.99, 4.50};
Note: The initializer shorthand (
{...}) can only be used at the point of declaration. You cannot use it to reassign an existing array variable.
Accessing and Modifying Elements
Use square brackets with the index to read or write any element:
int[] temps = new int[4];
temps[0] = 72;
temps[1] = 68;
temps[2] = 75;
temps[3] = 70;
System.out.println("Day 3 temp: " + temps[2]);
temps[2] = 77; // update
System.out.println("Updated Day 3 temp: " + temps[2]);
Output:
Day 3 temp: 75
Updated Day 3 temp: 77
Warning: Accessing an index that is out of bounds throws
ArrayIndexOutOfBoundsExceptionat runtime. Always stay within0toarray.length - 1.
Traversing an Array
With a for Loop
The classic approach gives you full control over the index:
int[] nums = {10, 20, 30, 40, 50};
for (int i = 0; i < nums.length; i++) {
System.out.println("Index " + i + ": " + nums[i]);
}
Output:
Index 0: 10
Index 1: 20
Index 2: 30
Index 3: 40
Index 4: 50
With a for-each Loop
The for-each loop is cleaner when you only need the values:
int[] nums = {10, 20, 30, 40, 50};
for (int n : nums) {
System.out.print(n + " ");
}
Output:
10 20 30 40 50
Tip: Use the for-each loop when you do not need the index. Use the traditional for loop when you need to modify elements or track position.
Array Length
Every array exposes a length field (not a method — no parentheses) that returns its size:
int[] data = {3, 7, 1, 9, 4};
System.out.println("Length: " + data.length); // 5
See the Array length page for more details and common patterns.
Passing Arrays to Methods
Arrays are objects, so when you pass an array to a method, you pass a reference — changes inside the method affect the original array:
void doubleAll(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] *= 2;
}
}
int[] values = {1, 2, 3};
doubleAll(values);
System.out.println(values[0]); // 2
System.out.println(values[1]); // 4
System.out.println(values[2]); // 6
This is consistent with Java’s call by value semantics — the reference is copied, not the array contents.
Returning Arrays from Methods
Methods can return arrays just like any other type:
int[] buildRange(int start, int count) {
int[] range = new int[count];
for (int i = 0; i < count; i++) {
range[i] = start + i;
}
return range;
}
int[] r = buildRange(5, 4);
// r = {5, 6, 7, 8}
System.out.println(r[0] + ", " + r[3]); // 5, 8
Common Array Operations
Finding Min/Max
int[] scores = {88, 92, 75, 99, 84};
int max = scores[0];
for (int s : scores) {
if (s > max) max = s;
}
System.out.println("Max: " + max); // 99
Summing Elements
int[] nums = {1, 2, 3, 4, 5};
int sum = 0;
for (int n : nums) sum += n;
System.out.println("Sum: " + sum); // 15
Copying an Array
int[] original = {1, 2, 3};
int[] copy = new int[original.length];
System.arraycopy(original, 0, copy, 0, original.length);
copy[0] = 99;
System.out.println(original[0]); // 1 (unaffected)
System.out.println(copy[0]); // 99
Tip:
Arrays.copyOf()from the Arrays Utility Class is often more convenient thanSystem.arraycopy().
Under the Hood
When you write int[] arr = new int[5], here is what the JVM actually does:
- Stack frame — the local variable
arris a reference (4 or 8 bytes) stored on the current stack frame. - Heap allocation —
new int[5]allocates a contiguous block on the heap. For primitives, this is4 bytes × 5 = 20 bytesof raw int storage, plus a small object header (typically 12–16 bytes) that stores the type tag and thelengthfield. - Zero-initialization — the JVM guarantees the allocated memory is zeroed before your code can access it (that is why defaults work).
- Reference stored — the stack variable holds the memory address of this heap object.
Because all elements are contiguous in memory, random access is O(1) — the JVM computes the address of arr[i] as base_address + i * element_size in a single step. This makes arrays extremely cache-friendly for sequential traversal.
The length field is baked into the array object header at creation time and is final — there is no way to resize a Java array. If you need a resizable list, use ArrayList, which wraps an array internally and copies to a larger one when capacity is exceeded.
Note: Java arrays are covariant — a
String[]is assignable to anObject[]variable. This is safe to read but can throwArrayStoreExceptionat runtime if you try to store a non-String value into theObject[]reference. This is one reason Generics preferList<T>over raw arrays for type safety.
Arrays vs. Other Collection Types
| Feature | Array | ArrayList | LinkedList |
|---|---|---|---|
| Size | Fixed | Dynamic | Dynamic |
| Element type | Primitive or Object | Object only (boxed) | Object only (boxed) |
| Access by index | O(1) | O(1) | O(n) |
| Insert/delete at middle | O(n) — manual shift | O(n) — internal shift | O(1) at node |
| Memory overhead | Lowest | Low (header + refs) | High (node objects) |
| Sorting utility | Arrays.sort() | Collections.sort() | Collections.sort() |
For most fixed-size, performance-critical work (math, image buffers, algorithms), arrays are the right choice. For flexible, general-purpose lists, prefer ArrayList.
In This Section
- Multidimensional Arrays — Create 2D and 3D arrays, model grids and matrices, and understand how nested arrays are laid out in memory.
- Array length — Understand the
lengthproperty, avoid off-by-one errors, and use it in loops and dynamic sizing patterns. - Jagged Arrays — Build arrays where each row has a different number of columns — perfect for triangular data or variable-length records.
- Arrays Utility Class — Use
Arrays.sort(),Arrays.binarySearch(),Arrays.copyOf(), and more fromjava.util.Arrays. - Array of Objects — Store instances of your own classes in arrays and understand reference vs. value semantics.
- String Arrays — Work with arrays of
Stringvalues, sort them, search them, and convert between arrays and lists. - Reverse an Array — Step-by-step techniques to reverse an array in-place and using utility methods.
- Array Programs — Practice problems and worked examples to solidify your array skills.
Related Topics
- Multidimensional Arrays — extend arrays to two or more dimensions for grid-based data.
- ArrayList — the go-to dynamic alternative to arrays, backed by an array internally.
- Arrays Utility Class — sort, search, copy, and fill arrays with one-liner utility methods.
- for-each Loop — the cleanest way to iterate every element of an array.
- Data Types — understand the primitive and reference types you can store in arrays.
- Generics — see why
List<T>is often preferred over raw arrays for type-safe collections.