Skip to content
Codewilds

Lesson 13 of 34 · Arrays & ArrayList

Java Arrays and the for-each Loop

easy10 XP3 min read

A single variable holds a single value. But a leaderboard has many scores, a dungeon has many rooms, and a shopping cart has many prices. An array stores a fixed number of values of the same type under one name, and loops let you process all of them with a few lines of code.

Creating an array

int[] scores = {90, 72, 85};        // an array literal with 3 elements
double[] prices = new double[5];    // 5 elements, all 0.0
String[] names = new String[3];     // 3 elements, all null

The type int[] reads "array of int". With new, every element starts with a default value: 0 for numbers, false for boolean, and null for objects such as String. An array's size is fixed when it is created — it can never grow or shrink.

Indexes start at 0

Each element has an index, its position counted from zero:

int[] scores = {90, 72, 85};
System.out.println(scores[0]);                  // 90 (the first element)
scores[1] = 75;                                 // replace the second element
System.out.println(scores.length);              // 3
System.out.println(scores[scores.length - 1]);  // 85 (the last element)

The valid indexes are 0 to length - 1. Reading scores[3] stops the program with an ArrayIndexOutOfBoundsException. Note that length is a field, written without parentheses — unlike the length() method of a String.

Printing an array

System.out.println(scores) prints something cryptic such as [I@6d06d69c — the array's type and an identity code, not its contents. Use the Arrays helper class instead:

import java.util.Arrays;

System.out.println(Arrays.toString(scores));   // [90, 75, 85]

Looping: for and for-each

The classic for loop walks through the indexes:

int total = 0;
for (int i = 0; i < scores.length; i++) {
    total += scores[i];
}

When you only need the values, the enhanced for loop (for-each) is shorter and cannot go out of bounds:

for (int score : scores) {
    System.out.println(score);
}

Read it as "for each score in scores". Use the classic loop when you need the index: to report a position, to change elements (scores[i] = 0;), to compare neighbours, or to walk backwards. Assigning to the for-each variable only changes the loop variable, never the array.

Arrays are references

An array variable does not contain the elements; it refers to an array object. Assigning it copies the reference, not the data:

int[] a = {1, 2, 3};
int[] b = a;          // b refers to the SAME array
b[0] = 99;
System.out.println(a[0]);                // 99!

int[] c = Arrays.copyOf(a, a.length);    // a real, independent copy
c[1] = 0;
System.out.println(Arrays.toString(a));  // [99, 2, 3]

For the same reason, a method that receives an array can change its elements, and a == c compares references. To compare contents, use Arrays.equals(a, c).

Common mistakes

  • Off-by-one loops: i <= numbers.length runs one step too far. The condition is i < numbers.length.
  • numbers.length(): arrays have a length field, no parentheses.
  • Starting a maximum at 0: with {-5, -2, -8} the answer would wrongly be 0. Start from numbers[0].
  • Modifying the input by accident: int[] result = numbers; does not copy. Create a new array.

Assignment

Write five static methods in Main:

  1. sum(int[] numbers) — the total of all elements; an empty array gives 0.
  2. max(int[] numbers) — the largest element (the array has at least one element).
  3. countAbove(int[] numbers, int limit) — how many elements are strictly greater than limit.
  4. indexOf(int[] numbers, int target) — the index of the first element equal to target, or -1 if there is none.
  5. doubled(int[] numbers) — a new array with every element multiplied by 2. The input array must not change.
sum(new int[]{4, 8, 15, 16, 23, 42})        // 108
max(new int[]{-5, -2, -8})                  // -2
countAbove(new int[]{5, 12, 7, 20, 12}, 10) // 3
indexOf(new int[]{7, 3, 9, 3}, 3)           // 1
doubled(new int[]{1, 2, 3})                 // [2, 4, 6]

Premium lesson

Unlock the full Learn Java course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Arrays and lists in other languages

Need a quick reminder? The Java cheat sheet has every topic of Learn Java on one page.

Lesson last updated on .

Write code ↓
Java+10 XP

Lesson 13 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn Java course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.