Skip to lesson

Common mistakes and practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Most array bugs are one of a few kinds: an index outside the array, a loop that starts or stops one place off, or two names for one array mistaken for a copy. Spot them quickly, then put the whole module to work on real problems.

Mistakes and fixes at a glance

Most array bugs come from the index: where a loop starts, where it stops, or one step past the end. The commonest is off-by-one: a loop that runs one round too many or too few.

Example · Off-by-one: starting at 1 skips an element

SkipFirst.javaJava
public class SkipFirst {    public static void main(String[] args) {        int[] runs = {6, 12, 4};        int wrong = 0;        for (int i = 1; i < runs.length; i++) {   // skips runs[0]            wrong += runs[i];        }        int right = 0;        for (int i = 0; i < runs.length; i++) {            right += runs[i];        }        System.out.println("Starting at 1: " + wrong);        System.out.println("Starting at 0: " + right);    }}
Output
Starting at 1: 16
Starting at 0: 22

What this code does

  • The first loop never reads runs[0], so the 6 runs of over 1 are missing from the total.
  • There is no error message, so this bug is easy to miss. Check every loop against the safe pattern: start at 0, stop with i < a.length.

Review: Looping through an array (opens in a new tab). The other common mistakes, each with what goes wrong and the fix:

Spot the bug

Each program below looks almost right but does the wrong thing. Read what it should do, tap the line that is wrong, then check the fix.

Before you tap, ask three questions: which indexes does it touch, is it changing the array or a copy, and are two names sharing one array?

Find the bug

Find the array bug

Select the line that is wrong.

This should print all 4 marks.

Round 1 of 6

When in doubt, trace it

A program reverses an array in place, without a second array, and you want to be sure it is right. Trace it: write down the array after every step. Here two indexes walk towards each other, left from the start and right from the end, swapping as they go.

Trace the code

Reverse an array in place

import java.util.Arrays;
public class ReverseInPlace {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5};
int left = 0;
int right = a.length - 1;
while (left < right) {
int temp = a[left];
a[left] = a[right];
a[right] = temp;
left++;
right--;
}
System.out.println(Arrays.toString(a));
}
}

Variables

a
{1, 2, 3, 4, 5}

Output

(nothing printed yet)

Line 5Five numbers to reverse in place, without a second array.

Step 1 of 11

Finish up

Mark complete & continue

Next: Must-do problems: Arrays