Java Basics Applied Class

exercises
tutorial
java
recursion
control-flow

Applied class exercises for week 2, reviewing week 1’s 2026-02-26-course-overview-and-java-basics content (switch statements, arrays, recursion). Meant to be done without a computer — you’re welcome to look up Java/library information, but your group knowing the answer isn’t a substitute for individual competence.

On the HTML site, fill in each blank with your answer (as a quoted string, e.g. "46368"), then click Run Code to check it. In the PDF, the Working callout is shown as a static answer key instead (interactive checking needs a browser).

Question 1 — Numbers to Numbers

Implement a method, nameOf, with the signature public static String nameOf(int value). If 0 < value < 10, return the name of the number, otherwise return "??".

What does each call return?

nameOf(4) →

nameOf(7) →

nameOf(24) →

Task 0 — using switch:

public static String nameOf(int value) {
    return switch (value) {
        case 1 -> "One";
        case 2 -> "Two";
        case 3 -> "Three";
        case 4 -> "Four";
        case 5 -> "Five";
        case 6 -> "Six";
        case 7 -> "Seven";
        case 8 -> "Eight";
        case 9 -> "Nine";
        default -> "??";
    };
}

The modern -> switch expression syntax is preferred over a traditional switch statement because it avoids one case accidentally falling through into the next if a break is omitted.

The traditional statement form, for comparison, needs a result variable and a break in every arm:

public static String nameOf(int value) {
    String result;

    switch (value) {
        case 1:
            result = "One";
            break;
        ...
        default:
            result = "??";
    }
    return result;
}

Task 1 — using an array of strings. The array is indexed from 0 but the names start at 1, hence the value - 1:

public static String nameOf(int value) {
    String[] numbers = {"One", "Two", ... };

    String result = "??";
    if (value > 0 && value < 10) {
        result = numbers[value - 1];
    }
    return result;
}

An equivalent early exit version deals with the exceptional case first, so the rest of the method is just the primary behaviour:

public static String nameOf(int value) {
    if (value <= 0 || value >= 10) {
        return "??";
    }

    String[] numbers = {"One", "Two", ... };
    return numbers[value - 1];
}

Bonus — extending to 10-99, using tiered helpers. Each helper is narrow enough to be a plain array lookup, and carries its own precondition as a Requires: Javadoc comment (the course’s specification style — see java-specification) rather than checking it at runtime; nameOf is then just the dispatcher that guarantees those preconditions hold:

/** Requires: value > 0 && value < 10 **/
private static String ones(int value) {
    String[] numbers = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
    return numbers[value - 1];
}

/** Requires: value >= 10 && value < 20 **/
private static String teens(int value) {
    String[] numbers = {"Ten", "Eleven", /* ... */};
    return numbers[value - 10];
}

/** Requires: value >= 20 && value < 100 **/
private static String tens(int value) {
    String[] numbers = {"Twenty", "Thirty", /* ... */};
    return numbers[value / 10 - 2];
}

public static String nameOf(int value) {
    if (value > 0 && value < 10) {
        return ones(value);
    }
    if (value >= 10 && value < 20) {
        return teens(value);
    }
    if (value >= 20 && value < 100) {
        if (value % 10 == 0) {
            return tens(value);
        } else {
            return tens(value) + " " + ones(value % 10);
        }
    }
    return "??";
}

Question 2 — Fibonacci Sequence

The Fibonacci sequence (\(0, 1, 1, 2, 3, \ldots\)) is defined as \(\mathcal{F}(0)=0\), \(\mathcal{F}(1)=1\), \(\mathcal{F}(n) = \mathcal{F}(n-1) + \mathcal{F}(n-2)\) for \(n \geq 2\): 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...

Implement public static int fib(int n), returning the \(n\)th element — so fib(1) → 1 and fib(2) → 1. What is fib(24)?

public static int fib(int n) {
    if (n <= 1) {
        return n;
    }
    return fib(n - 1) + fib(n - 2);
}

fib(24) → 46368.

Desk check. A desk check is a manual (non-computerised) technique for checking the logic of an algorithm: the person performing the check effectively acts as the computer, using pen and paper to record results.

The desk check of fib(6) below is a graph with one node per distinct call rather than a full call tree, and one arrow per return:

Figure 1: A desk check of fib(6). Each node is one distinct call F(k); each arrow runs from a callee back to its caller and is labelled with the value that call returned, so a node’s own value is the sum of the two labels entering it (F(6) receives 5 from F(5) and 3 from F(4), giving 8). Repeated calls are collapsed: fib’s recursion really evaluates F(4) twice, F(3) three times and so on, but only one node per k is drawn, so what is pictured is the dependency DAG rather than the call tree.

Reading Figure 1 bottom-right to top-left is exactly the order the recursion unwinds: the base cases F(1) = 1 and F(0) = 0 return first, and every other node adds the two labels arriving at it. That is also the reason this implementation is slow — the picture hides the fact that the collapsed nodes are recomputed from scratch on every visit.

Question 3 — The Collatz Conjecture

Start with any positive integer \(n\): if even, divide by 2; if odd, multiply by 3 and add 1; repeat. The (unproven, but checked below \(2075 \times 2^{60}\) as of 2025) conjecture is that this always reaches 1.

Implement public static int collatz(int n), returning the number of steps to reach 1 — so collatz(1) → 0, since 1 is already there. Sketch the process before writing any code; a flow chart is a good start. What is collatz(3)?

The process the method has to run is a single loop with a two-way test inside it:

Figure 2: The Collatz step as a flow chart, in the ordinary flow-chart conventions (rounded terminator, rectangle for a process step, diamond for a decision). Every box corresponds to exactly one line of the solution: the counter increments once per iteration, after the branch and before the test is re-evaluated, which is why collatz(1) is 0 and not 1.

Transcribing Figure 2 gives the solution directly:

public static int collatz(int n) {
    int steps = 0;
    while (n != 1) {
        if (n % 2 == 0) {
            n = n / 2;
        } else {
            n = 3 * n + 1;
        }
        steps++;
    }
    return steps;
}

Trace for collatz(3): 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1, which is 7 steps.

Worked examples:

call result
collatz(1) 0
collatz(2) 1
collatz(3) 7
collatz(4) 2

Question 4 — Ackermann function (extra)

The Ackermann–Péter function: \(\mathcal{A}(m,n) = n+1\) if \(m=0\); \(\mathcal{A}(m-1, 1)\) if \(m>0, n=0\); \(\mathcal{A}(m-1, \mathcal{A}(m, n-1))\) if \(m>0, n>0\).

Implement public long ackermann(short m, short n), and explain why it takes short parameters but returns a long.

The direct transcription of the three cases has one if per line of the definition:

public long ackermann(short m, short n) {
    if (m == 0) {
        return n + 1;
    }

    if (m > 0 && n == 0) {
        return ackermann(m - 1, 1);
    }

    if (m > 0 && n > 0) {
        return ackermann(m - 1, ackermann(m, n - 1));
    }
}

This does not actually compile, because of Java’s implicit type promotion (see java-casting, covered later in the course): arithmetic on short operands (m - 1, n - 1) promotes them to int, which is not assignable back to a short parameter. The compiling version adds an explicit (short) cast at every recursive call, plus a final return so that every path returns a value:

public long ackermann(short m, short n) {
    if (m == 0) {
        return n + 1;
    }

    if (m > 0 && n == 0) {
        return ackermann((short) (m - 1), (short) 1);
    }

    if (m > 0 && n > 0) {
        return ackermann((short) (m - 1),
                          (short) ackermann(m, (short) (n - 1)));
    }

    return -1; // Impossible case but required for coverage.
}

Why short in, long out? The Ackermann function grows extremely rapidly even for small inputs, so the parameters are restricted to short (deliberately small inputs) while the result is a long, so the (much larger) output can be represented without overflow.