SyntaxPilot
Courses/Java/Lesson 7

Java · Lesson 7 of 51 · 12 min

Arrays: declare, traverse, enhanced for

queued

These are the notes for Java episode 7. You will learn why one variable per student breaks, what an array is (one name, numbered slots of one type), indexes starting at 0 and length, why println(marks) prints [I@..., the ArrayIndexOutOfBoundsException, traversing an array with for, new int[n] and default values, filling an array from the keyboard, the for-each loop and why it can't change the array, and why int[] copy = marks; doesn't copy anything. Every example below runs as-is in the SyntaxPilot compiler, with its real output from javac 21.

The problem: one variable per student

A class teacher stores exam marks in m1, m2, m3, m4, m5. A real class has 60 students: 60 variables, and every total is typed by hand: m1 + m2 + ... + m60. Loops (episode 6) should help, so let's try making the loop pick the variable:

public class Main {
    public static void main(String[] args) {
        int m1 = 78, m2 = 92, m3 = 65, m4 = 88, m5 = 71;
        int total = 0;
        for (int i = 1; i <= 5; i++) {
            total += m + i;
        }
    }
}
Main.java:6: error: cannot find symbol
            total += m + i;
                     ^
  symbol:   variable m
  location: class Main
1 error

Why it failed: m + i means "a variable called m, plus i". Java never glues letters together to build a variable's name. A loop can change a number, never a name. We need one name with numbered slots, so the loop can change the number.

What an array is

Real-life example: a train. The whole train has one name (Rajdhani Express); its coaches are numbered and all the same kind. And in India the ground floor is floor 0: the first floor is one level up.

On the railway In Java
one train name one array variable: int[] marks
numbered coaches, all alike elements of one type: marks[0], marks[1], ...
the coach number the index
ground floor = 0 the first index is 0

An array is a fixed-size, numbered group of values of the same type, under one name.

marks →  [ 78 ][ 92 ][ 65 ][ 88 ][ 71 ]
index      0     1     2     3     4        length = 5

Declaring an array, index and length

public class Main {
    public static void main(String[] args) {
        int[] marks = {78, 92, 65, 88, 71};
        System.out.println("First: " + marks[0]);
        System.out.println("Third: " + marks[2]);
        System.out.println("Count: " + marks.length);
    }
}
First: 78
Third: 65
Count: 5
  • int[] means "array of int". The { ... } list is an array initializer.
  • marks[i] reads (or writes) the element at index i.
  • marks.length is how many elements there are (no brackets: it's a field, not a method).
  • Indexes go from 0 to length - 1.

Printing an array directly

int[] marks = {78, 92, 65, 88, 71};
System.out.println(marks);
[I@2a139a55

(The number changes from run to run.) [I means "array of int" and the number after @ is a hash code that identifies the array object, not the values. To see the values, loop over the array, or use Arrays.toString(marks) (episode 8).

Index out of bounds

int[] marks = {78, 92, 65, 88, 71};
System.out.println(marks[5]);
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
    at Main.main(Main.java:4)

This compiles; it crashes while running. There is no slot 5: the last one is 4. Negative indexes (marks[-1]) crash the same way.

Traversing an array with a for loop

Going through every element once is called traversing the array. Start at 0, stop before length:

public class Main {
    public static void main(String[] args) {
        int[] marks = {78, 92, 65, 88, 71};
        int total = 0;
        for (int i = 0; i < marks.length; i++) {
            System.out.println("Roll " + i + ": " + marks[i]);
            total += marks[i];
        }
        System.out.println("Average: " + (double) total / marks.length);
    }
}
Roll 0: 78
Roll 1: 92
Roll 2: 65
Roll 3: 88
Roll 4: 71
Average: 78.8
  • i < marks.length, not <=: <= reaches index 5 and throws ArrayIndexOutOfBoundsException (the off-by-one bug from episode 6).
  • Use marks.length, never a typed number: the same loop works for 5 or 60 students.
  • (double) before dividing gives the exact average (episode 4).

new int[n] and default values

Usually the values come later (after the exam). Create an empty array of a chosen size with new (like buying an empty egg tray: the size is fixed now, the eggs come later):

public class Main {
    public static void main(String[] args) {
        int[] marks = new int[3];
        String[] names = new String[3];
        double[] heights = new double[3];
        boolean[] present = new boolean[3];
        System.out.println(marks[0] + " " + names[0] + " " + heights[0] + " " + present[0]);
    }
}
0 null 0.0 false
Element type Default value
int, long, short, byte 0
double, float 0.0
char '\u0000' (the "null character")
boolean false
String and other objects null (no object at all)

The length is fixed once the array is created. Need a 61st student? Make a new, bigger array and copy. ArrayList (later in the course) grows by itself.

Filling an array from the keyboard and changing one element

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] marks = new int[3];
        for (int i = 0; i < marks.length; i++) {
            marks[i] = sc.nextInt();
        }
        marks[2] = marks[2] + 5;
        for (int i = 0; i < marks.length; i++) {
            System.out.println("Roll " + i + ": " + marks[i]);
        }
    }
}

Input 78 92 35:

Roll 0: 78
Roll 1: 92
Roll 2: 40

marks[i] = value writes one slot; marks[2] = marks[2] + 5 gives roll 2 five grace marks.

The for-each (enhanced for) loop

for (int m : marks) reads as "for each m in marks". No index, no length, no off-by-one. Java hands you each value in turn.

public class Main {
    public static void main(String[] args) {
        int[] marks = {78, 92, 65, 88, 71};
        int max = marks[0];
        for (int m : marks) {
            if (m > max) {
                max = m;
            }
        }
        System.out.println("Topper: " + max);
    }
}
Topper: 92

Start max at the first element (not 0, which would be wrong if all marks were negative).

The for-each trap: m is a copy

public class Main {
    public static void main(String[] args) {
        int[] marks = {78, 92, 65, 88, 71};
        for (int m : marks) {
            m = m + 5;
        }
        for (int m : marks) {
            System.out.print(m + " ");
        }
    }
}
78 92 65 88 71 

Nothing changed. m is a copy of each value (a photocopy of the answer sheet); changing it doesn't touch the array. To change elements, use an index:

for (int i = 0; i < marks.length; i++) {
    marks[i] = marks[i] + 5;
}
Need Use
just read every value for-each
the index (roll number), or to change elements normal for with i
go backwards, or skip some indexes normal for

Two names, one array

public class Main {
    public static void main(String[] args) {
        int[] marks = {78, 92, 65, 88, 71};
        int[] copy = marks;
        copy[0] = 100;
        System.out.println(marks[0]);
    }
}
100

int[] copy = marks; does not copy the array. An array variable holds a reference (the address of the array object), so now two names point to the same array, like giving the same train a second name. To really copy, make a new array and copy element by element (or use Arrays.copyOf, episode 8). You'll meet references in depth with objects.

Common mistakes (and the real error messages)

Mistake Real message Why Fix
marks[5] when length is 5 ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 indexes are 0 to length-1 i < marks.length
System.out.println(marks); [I@2a139a55 prints type + hash code loop, or Arrays.toString
int marks[5]; ']' expected the size goes after new int[] marks = new int[5];
marks = {1, 2, 3}; on a later line illegal start of expression { } alone only works in the declaration marks = new int[]{1, 2, 3};
total += m + i; with m1..m5 cannot find symbol symbol: variable m names can't be built in a loop use an array
changing m in a for-each no error, array unchanged m is a copy index-based for
int[] b = a; to copy no error, both change together it copies the reference copy element by element

Mini project: class result

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("How many students?");
        int n = sc.nextInt();
        int[] marks = new int[n];
        for (int i = 0; i < n; i++) {
            marks[i] = sc.nextInt();
        }
        int total = 0, max = marks[0], passed = 0;
        for (int m : marks) {
            total += m;
            if (m > max) {
                max = m;
            }
            if (m >= 40) {
                passed++;
            }
        }
        System.out.println("Average: " + (double) total / n);
        System.out.println("Topper: " + max);
        System.out.println("Passed: " + passed + " of " + n);
    }
}

Input 6 then 78 92 35 88 71 39:

How many students?
Average: 67.16666666666667
Topper: 92
Passed: 4 of 6

The array is created with exactly n slots, so the same code works for any class size. Extend it: also print the roll number of the topper (track the index, not just the value) and the lowest mark.

Practice

  1. Read 5 numbers into an array and print them in reverse order.
  2. Find the lowest mark and its roll number (index).
  3. Count how many numbers in an array are even.
  4. Copy an array into a new array with a loop, change the copy, and show the original is unchanged.
  5. Check whether an array is sorted in increasing order.
Solutions and hints
  1. for (int i = a.length - 1; i >= 0; i--) System.out.print(a[i] + " ");
  2. java int minIdx = 0; for (int i = 1; i < marks.length; i++) { if (marks[i] < marks[minIdx]) { minIdx = i; } } System.out.println("Lowest: " + marks[minIdx] + " (roll " + minIdx + ")");
  3. int c = 0; for (int x : a) { if (x % 2 == 0) { c++; } }
  4. java int[] b = new int[a.length]; for (int i = 0; i < a.length; i++) { b[i] = a[i]; } b[0] = 999; // a[0] is unchanged
  5. Compare neighbours: for (int i = 1; i < a.length; i++) if (a[i] < a[i - 1]) sorted = false; (start i at 1 so a[i - 1] exists).

Quick quiz

What does this print?

int[] a = {3, 6, 9};
System.out.println(a[a.length - 1] + a[0]);
  • A. 9
  • B. 12
  • C. 39
  • D. ArrayIndexOutOfBoundsException
Answer

B. 12. a.length is 3, so a[a.length - 1] is a[2], the last element, 9. Plus a[0] (3) is 12. Both are ints, so + adds (it would join only if one side were a String).

Interview questions

  1. Why do array indexes start at 0? The index is the offset from the start of the array: the first element is 0 steps from the start.
  2. What is the default value of elements in new int[5]? In new String[5]? 0; null.
  3. Is length a method or a field? For arrays, a field: a.length. For a String, a method: s.length().
  4. Can an array's size change? No; create a new array (or use ArrayList).
  5. What does int[] b = a; do? Copies the reference; a and b are the same array.
  6. Can you change array elements with a for-each loop? Not primitive elements: the loop variable is a copy.
  7. Is ArrayIndexOutOfBoundsException checked at compile time? No, it's a runtime exception.

Glossary

Term Meaning Example
array a fixed-size, numbered group of values of one type under one name int[] marks
element one value stored in an array 92
index the position number of an element, starting at 0 marks[1]
length how many elements an array has marks.length → 5
array initializer the { ... } list that creates and fills an array {78, 92, 65}
new int[n] creates an array of n slots filled with default values new int[60]
default value the value an unset element has 0, null, 0.0, false
null "no object at all" an empty String[] slot
traverse visit every element once for (int i = 0; i < a.length; i++)
ArrayIndexOutOfBoundsException the runtime crash for an index outside 0..length-1 marks[5]
for-each (enhanced for) loop visits each value without an index for (int m : marks)
reference a variable's link to an array or object in memory int[] copy = marks;
hash code the number after @ in [I@2a139a55 printing an array

Summary

  • An array is one name with numbered slots of one type; make it with {...} or new int[n].
  • Indexes start at 0; the last is length - 1; going past it throws ArrayIndexOutOfBoundsException.
  • Traverse with for (int i = 0; i < a.length; i++).
  • Empty slots hold default values, and the length is fixed.
  • For-each reads copies; use an index to change elements.
  • b = a shares the array; it doesn't copy it.

Next episode: 2D arrays (tables of rows and columns) and the java.util.Arrays toolbox: toString, sort, fill, copyOf.