Java Arrays
An array stores a fixed number of values of the same type in a single variable. Instead of declaring score1, score2, score3, you declare one array scores and reach each value by its position. This lesson covers the essentials; the Arrays and Collections section later covers copying, sorting, searching, and multidimensional arrays in depth.
Declaring and Creating Arrays
int[] scores = new int[5]; // five ints, all 0
String[] names = new String[3]; // three Strings, all null
double[] prices = {19.99, 5.49, 120.0}; // created and filled in one step
Reading the declaration int[] scores: the type is int[] ("array of int"), and the variable is scores.
There are two ways to create an array:
| Form | When to use | Example |
|---|---|---|
new Type[size] | Size known, values filled in later | new int[100] |
{v1, v2, ...} | Values known when writing the code | {"red", "green", "blue"} |
The brace form (an array initializer) works only in a declaration. To assign a new array to an existing variable, include new and the type:
int[] nums;
nums = {1, 2, 3}; // compile error
nums = new int[]{1, 2, 3}; // correct
Java also accepts the C-style int scores[], but int[] scores keeps the whole type in one place and is the standard style.
Default Values
An array created with new has every element set to the type's default:
| Element type | Default |
|---|---|
int, long, short, byte | 0 |
double, float | 0.0 |
boolean | false |
char | '\u0000' |
Any object type (String, etc.) | null |
String[] names = new String[3];
System.out.println(names[0]); // null
System.out.println(names[0].length()); // NullPointerException
An array of objects holds references, which start as null. Each element must be assigned an object before it is used.
Accessing Elements
Elements are numbered from 0. An array of length 5 has indexes 0 through 4.
index: 0 1 2 3 4
[ 90 ][ 75 ][ 88 ][ 62 ][ 95 ]
int[] scores = {90, 75, 88, 62, 95};
System.out.println(scores[0]); // 90 (first)
System.out.println(scores[4]); // 95 (last)
scores[1] = 80; // replace the second element
System.out.println(scores[1]); // 80
Indexing starts at 0 because the index is an offset from the start of the array: the first element is zero positions from the beginning.
Out-of-bounds access
Java checks every index at runtime. An index below 0 or at or beyond the length throws an exception:
int[] a = new int[3];
a[3] = 10; // ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
In C, the same write would silently overwrite other memory. Java's bounds checking turns that class of bug into an immediate, clear error.
Length
Every array has a length field giving its number of elements:
String[] colors = {"red", "green", "blue"};
System.out.println(colors.length); // 3
System.out.println(colors[colors.length - 1]); // blue (last element)
length is a field, not a method: no parentheses. (Strings use length(), a method; collections use size(). The inconsistency is historical.)
An array's length is fixed when it is created and cannot change. To hold more elements, you must create a new, larger array and copy the values over, which is exactly what ArrayList does internally. When the number of items is not known in advance, use ArrayList instead of an array.
Looping Through an Array
double[] prices = {19.99, 5.49, 120.0, 42.5};
// index loop: when the position is needed
for (int i = 0; i < prices.length; i++) {
System.out.println("Item " + (i + 1) + ": " + prices[i]);
}
// enhanced for loop: when only the values are needed
double total = 0;
for (double p : prices) {
total += p;
}
System.out.printf("Total: %.2f%n", total);
The loop condition i < prices.length stops exactly after the last valid index. Writing i <= prices.length is a classic off-by-one error that throws on the final iteration.
Common Operations
Finding the maximum
int[] temps = {31, 34, 29, 36, 33};
int max = temps[0];
for (int i = 1; i < temps.length; i++) {
if (temps[i] > max) {
max = temps[i];
}
}
System.out.println("Highest: " + max); // 36
max starts at the first element rather than 0, so the result is correct even if every value is negative. The loop then starts at index 1, since index 0 is already accounted for. (This assumes the array is not empty.)
Counting matches
int[] marks = {72, 45, 88, 39, 91, 55};
int passed = 0;
for (int m : marks) {
if (m >= 50) passed++;
}
System.out.println(passed + " of " + marks.length + " passed"); // 4 of 6 passed
The Arrays Utility Class
java.util.Arrays provides static methods for everyday array tasks:
import java.util.Arrays;
int[] nums = {5, 3, 9, 1, 7};
System.out.println(Arrays.toString(nums)); // [5, 3, 9, 1, 7]
Arrays.sort(nums);
System.out.println(Arrays.toString(nums)); // [1, 3, 5, 7, 9]
int idx = Arrays.binarySearch(nums, 7); // 3 (array must be sorted)
int[] filled = new int[4];
Arrays.fill(filled, -1); // [-1, -1, -1, -1]
int[] bigger = Arrays.copyOf(nums, 7); // [1, 3, 5, 7, 9, 0, 0]
boolean same = Arrays.equals(nums, new int[]{1, 3, 5, 7, 9}); // true
Printing an array directly gives something like [I@1b6d3586 (a type code and hash), not its contents, because arrays do not override toString. Use Arrays.toString for display.
Similarly, == and equals on arrays compare identity, not contents. Use Arrays.equals to compare element by element.
Arrays Are Reference Types
An array variable holds a reference to the array object. Assigning it to another variable copies the reference, not the elements:
int[] original = {1, 2, 3};
int[] alias = original;
alias[0] = 99;
System.out.println(original[0]); // 99: both variables refer to one array
int[] copy = original.clone(); // or Arrays.copyOf(original, original.length)
copy[1] = 50;
System.out.println(original[1]); // 2: the copy is independent
The same applies when passing an array to a method: the method receives a reference and can change the caller's array.
static void doubleAll(int[] values) {
for (int i = 0; i < values.length; i++) {
values[i] *= 2;
}
}
int[] data = {1, 2, 3};
doubleAll(data);
System.out.println(Arrays.toString(data)); // [2, 4, 6]
Two-Dimensional Arrays (Preview)
An array can hold other arrays, forming a grid:
int[][] seats = {
{1, 0, 1},
{0, 0, 1}
};
System.out.println(seats[1][2]); // 1: row 1, column 2
System.out.println(seats.length); // 2 rows
System.out.println(seats[0].length); // 3 columns in row 0
Multidimensional arrays have their own lesson.
Arrays Versus ArrayList
| Array | ArrayList | |
|---|---|---|
| Size | Fixed at creation | Grows and shrinks |
| Element types | Primitives or objects | Objects only (Integer, not int) |
| Syntax | a[i], a.length | list.get(i), list.size() |
| Performance | Lowest overhead; primitives stored directly | Small overhead; boxing for numbers |
| Typical use | Fixed-size data, numeric work, low-level code | Most application code where size varies |
Practical Example: Weekly Step Tracker
import java.util.Arrays;
public class StepTracker {
public static void main(String[] args) {
String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
int[] steps = {8200, 10450, 6300, 12000, 9100, 15200, 4300};
int goal = 10_000;
int total = 0;
int goalDays = 0;
int bestDay = 0;
for (int i = 0; i < steps.length; i++) {
total += steps[i];
if (steps[i] >= goal) {
goalDays++;
}
if (steps[i] > steps[bestDay]) {
bestDay = i;
}
}
double average = (double) total / steps.length;
System.out.println("Steps: " + Arrays.toString(steps));
System.out.printf("Average: %.0f%n", average);
System.out.println("Goal reached: " + goalDays + " of " + days.length + " days");
System.out.println("Best day: " + days[bestDay] + " (" + steps[bestDay] + ")");
}
}
Output:
Steps: [8200, 10450, 6300, 12000, 9100, 15200, 4300]
Average: 9364
Goal reached: 3 of 7 days
Best day: Sat (15200)
Two parallel arrays share indexes: days[i] names the day whose count is steps[i]. The loop uses an index so it can track which day is best (bestDay) rather than only the best value. (double) total / steps.length prevents integer division. Parallel arrays are fine for small examples; in larger programs, a record such as record DayStats(String day, int steps) in a single array or list keeps related values together.