bhylu.com

Advertisements

Java Exercises: Trace, Repair and Extend

Practise three related skills: tracing an array calculation, repairing a boundary condition and extracting a method with a clear return contract. Try the tasks before reading the worked example.

Your brief

Task one: find the smallest positive seat request in 0, 5, -2, 3 and explain which values are excluded. Task two: repair a loop that uses index <= length; describe why the last access is invalid. Task three: return OptionalInt.empty when no positive request exists. The worked method below solves the first and third tasks together. It has no printing inside the search, so a caller can decide how to display a missing result. Empty arrays and arrays containing only zero or negative values belong in the tests, not just the happy path.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

Worked solution

Show the worked solution
Java 21+ · Main.java

import java.util.OptionalInt;

public class Main {
    static OptionalInt smallestPositive(int[] values) {
        OptionalInt result = OptionalInt.empty();
        for (int value : values) {
            if (value > 0 && (result.isEmpty() || value < result.getAsInt()))
                result = OptionalInt.of(value);
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(smallestPositive(new int[]{0, 5, -2, 3}).orElse(-1));
        System.out.println(smallestPositive(new int[]{0, -2}).isEmpty());
        if (smallestPositive(new int[]{}).isPresent()) throw new AssertionError("Empty input");
    }
}

Expected output

3
true

The empty optional means no qualifying value has been found. A positive value replaces it if it is the first candidate or is smaller than the previous candidate. Short-circuit evaluation prevents getAsInt from being called on an empty optional. The enhanced loop avoids indexing altogether. Returning an optional distinguishes a missing result from a valid numeric answer without choosing a sentinel inside the method.

Extend and test

Write tests for one positive value, repeated minima and a positive value at the final position. Extend the method to accept an IntPredicate and discuss whether that makes this small task clearer.

Check the official Java documentation for detailed contracts and supported options.

Advertisements