Sub topic 8
Working with Arrays
So far, each variable you have written held exactly one value: one int, one String, one boolean. That works fine for a few values. But what if you need to store the test scores of 30 students, or the names of 12 months? Writing int score1, int score2, int score3... all the way to 30 would be painful and error-prone.
An array is a container that holds a fixed number of values of the same type, all in a row. Instead of 30 separate variables, you create one array with 30 slots. Each slot holds one value, and you can reach any slot by its position number.
This chapter assumes you are comfortable with variables and primitive types (like int and double), and with for loops. If you can write a loop that prints numbers 1 through 5, you are ready.
What an Array Is
Think of an array like an egg carton:
- It has a fixed number of slots, decided when you create it.
- Every slot holds the same kind of thing (all
ints, or allStrings). - Each slot has a position, called an index, that lets you find it directly.
The key fact about indices, and the single most common source of beginner confusion, is this: array indices start at 0, not 1. The first element is at index 0, the second at index 1, and the last is at index (length − 1). If an array has 5 elements, valid indices are 0, 1, 2, 3, and 4.
Creating and Using an Array
There are two common ways to create an array.
Way 1: `new` with a size
Use new, the type, and the number of elements in square brackets:
int[] scores = new int[3];This creates an array of 3 ints. Java fills numeric arrays with zeros automatically, so right now it holds {0, 0, 0}. Then you assign values one slot at a time, using the index in square brackets:
scores[0] = 85;
scores[1] = 92;
scores[2] = 78;Way 2: An initializer list
If you already know the values, list them between braces. Java counts them and sizes the array for you — do not put a number in the brackets here:
int[] scores = {85, 92, 78};Both ways produce the same thing: an array of length 3.
Reading and writing elements
Square brackets work for both directions:
- Write:
scores[1] = 92;puts 92 into slot 1 (the second slot). - Read:
int best = scores[1];copies the value out of slot 1.
You can also do math with an element, just like a normal variable:
scores[0] = scores[0] + 5; // bump the first score up by 5Every array carries a field called length, which tells you how many slots it has:
System.out.println(scores.length); // prints 3Note that length has no parentheses — it is a field, not a method. That trips up beginners because String uses length() with parentheses. Arrays use length, strings use length().
The Classic Error: ArrayIndexOutOfBoundsException
If you use an index that does not exist — negative, or equal to length or larger — Java stops your program with an exception (an error that interrupts execution) named ArrayIndexOutOfBoundsException.
int[] scores = {85, 92, 78};
System.out.println(scores[3]); // ERROR: valid indices are 0, 1, 2This is the array equivalent of walking into an egg carton with 12 slots and reaching for slot 13. It is extremely common in loops that go one step too far, which is why you will see i < arr.length far more often than i <= arr.length. If you see this exception, check the loop bounds and the index arithmetic first.
Looping Through an Array
Arrays and loops are made for each other. You almost never write scores[0], scores[1], scores[2] by hand.
The standard for loop
Use this when you need to know the index — for example, to print a position number:
int[] scores = {85, 92, 78};
for (int i = 0; i < scores.length; i++) {
System.out.println("Score " + i + " is " + scores[i]);
}Read the loop line as: start i at 0; keep going while i is less than the length; add 1 each time. Because the condition is i < scores.length, the last value of i is exactly length − 1 — the final valid index. Perfect fit.
The enhanced for loop (for-each)
If you do not need the index — you just want every value — use the enhanced for loop, also called a for-each loop. Read it as "for each int n in scores":
for (int n : scores) {
System.out.println(n);
}This is shorter and safer (no index to get wrong). The trade-off: you cannot easily know which position you are on, and you cannot reassign elements through n in a useful way. Rule of thumb: use for-each to read every element; use the standard loop when you need the index.
A Complete Worked Program
Here is a small program that ties it together: it computes the average of a set of scores and finds the highest one.
public class Scores {
public static void main(String[] args) {
int[] scores = {85, 92, 78, 95, 66};
// Total all values with a for-each loop
int total = 0;
for (int s : scores) {
total = total + s;
}
// Average: use a double so the decimal part is not lost
double average = (double) total / scores.length;
System.out.println("Average: " + average);
// Find the largest value with an indexed loop
int highest = scores[0];
for (int i = 1; i < scores.length; i++) {
if (scores[i] > highest) {
highest = scores[i];
}
}
System.out.println("Highest: " + highest);
}
}Two things to notice:
- Accumulator pattern:
totalstarts at 0 and each loop pass adds one value into it. This "running sum" pattern appears constantly with arrays. - Max-tracking pattern:
higheststarts as the first element, then each element that is bigger replaces it. Always start from an element (likescores[0]), never from 0 — starting from 0 would fail if all scores were negative.
Save the file as Scores.java, then compile and run it:
javac Scores.java
java ScoresOutput:
Average: 83.2
Highest: 95Arrays of Other Types
Arrays work with any type, not just int:
double[] prices = {4.99, 12.5, 3.75};
boolean[] flags = new boolean[4]; // all false
String[] names = {"Ada", "Grace", "Linus"};
for (String name : names) {
System.out.println("Hello, " + name);
}One warning about string arrays created with new: they start as null, a special value meaning "no object here". Printing a null string prints the word null, but calling a method on it crashes your program with a NullPointerException. Assign real values before using those slots.
Common Errors Checklist
- Wrong index bounds: valid indices run from
0tolength - 1. Off-by-one in a loop condition is the number-one array bug. lengthvslength(): arrays use the fieldlength; strings use the methodlength().- Putting a size in an initializer list:
new int[3] {1, 2, 3}is illegal — pick one style or the other. - Empty-division trap: computing an average from an empty (length 0) array divides by zero. Check the length first if your data might be empty.
- Assuming default values everywhere: numeric arrays start at 0 and boolean arrays at
false, but object arrays (likeString[]fromnew) start atnulland must be filled in.
Chapter Summary
- An array holds a fixed number of values of one type, stored in numbered slots.
- Indices start at 0; the last valid index is
length - 1. - Create with
new Type[size](slots start at default values) or with{v1, v2, ...}when you know the values. - Read and write with
arr[index]; find the size witharr.length. - Use an indexed
forloop when you need positions, and a for-each loop when you just need the values. - Going out of bounds throws
ArrayIndexOutOfBoundsException— check your loop conditions.
Exercise
An array is created with int[] data = new int[4];. What are the valid indices, what values do the slots hold right now, and what does data.length return?
Show answer
Valid indices are 0, 1, 2, and 3. All four slots hold 0 (the default for numeric types). data.length returns 4, because length counts elements while the highest index is one less.
Exercise
Rewrite this loop as a for-each loop: for (int i = 0; i < names.length; i++) { System.out.println(names[i]); }
Show answer
for (String n : names) { System.out.println(n); } — read it as "for each String n in names". You can drop the index because it is only used to fetch each element, not for anything index-specific like printing position numbers.
Exercise
This loop is meant to print every element of int[] a = {5, 6, 7}; but it crashes. Why? for (int i = 1; i <= a.length; i++) { System.out.println(a[i]); }
Show answer
It starts at index 1 (skipping the first element) and ends at a.length, which is 3 — not a valid index. The last valid index is a.length - 1. Fix it with for (int i = 0; i < a.length; i++).