CSSE2002 — Full Course Notes

Week 1

Course Overview and Java Basics

See csse2002 for staff, assessment, and course logistics. This is the technical content of Lecture 1, the live lecture. There’s also a recorded lecture this week, see 2026-02-26-java-basics-part-02-collections-and-strings.

Outline

  • Programming in the large vs. programming in the small — why this course isn’t just “a Java course”
  • Java vs Python: compiled vs interpreted, statically vs dynamically typed
  • Java’s primitive and reference types
  • Scope
  • Sequence, selection, and iteration in Java
  • Java arithmetic

Programming in the large

Code from an intro course (CSSE1001/ENGG1001) has likely been:

  1. Small.
  2. Written solely by you.
  3. For a limited purpose.
  4. To exist for a limited time.

…but large software projects are often none of these.

CSSE2002 teaches individual discipline and programming practices such that graduates can design and write software suitable for integration with large software systems. Professionally you will need to:

  • Document your code — because someone who didn’t write it (or doesn’t remember it) may need to work on it.
  • Debug your code — the more code you write, the more opportunity to make mistakes.
  • Test your code — it is far better for you to find bugs than for someone else to. You want a reason for confidence in your work beyond “I hope it is okay”.

CSSE2002 teaches practices that support documenting, debugging, and testing of code to allow programming to scale to large software projects.

This is not just a Java course. Knowing everything (or even most things) about Java is not the only goal. Java is the vehicle. As for why Java: in the Stack Overflow 2025 developer survey, Java is used by 29.6% of professional developers.

Where the course sits in the software lifecycle

In a seven-phase software development lifecycle, CSSE2002 lives in two of the phases, Phase 4 (Development) and Phase 5 (Testing):

Figure 1: A seven-phase software development lifecycle (SDLC), with a red rectangle around Phases 4–5: CSSE2002 is a development and testing course, not a requirements or deployment course.

Java overview

Java is a general-purpose programming language that is:

  • Compiled
  • Statically typed
  • Object-oriented
  • Memory safe

Java vs Python: compiled vs interpreted

Python is interpreted: you run the Python interpreter directly on the source.

$ python hello_world.py

Java is compiled: the source is first compiled to bytecode, then run.

$ javac HelloWorld.java
$ java HelloWorld

Hello World, with the canonical entry point:

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}

Running javac on it produces a .class file of bytecode. As raw hex, the file begins with the JVM’s cafebabe magic number:

cafebabe00000041001d0a000200030700040c000500060100106a617661
2f6c616e672f4f626a6563740100063c696e69743e010003282956090008
...

Homework. What is the benefit of having bytecode? What are the differences between bytecode and machine code?

Java vs Python: static vs dynamic typing

Python is dynamically typed — whether an appropriate type is used is determined when the program runs. Java is statically typed — types are checked for every scenario at compile time.

Static typed languages require explicit definition of a data type when they create a piece of data (e.g. variable, parameter, return value). Dynamic languages are the opposite and can infer, or at least try to guess, the type that we’re using.

x = 1
print(x, type(x))    # 1 <class 'int'>
x = 1.7
print(x, type(x))    # 1.7 <class 'float'>
x = "Hello"
print(x, type(x))    # Hello <class 'str'>

Python knows that 1 and 1.7 are different types of value (different “dynamic”/“runtime” types) but doesn’t restrict variables on that basis. Java is the opposite — the variable carries the type:

int x;
x = 1;      // OK
x = -5000;  // OK
x = 1.0;    // Illegal: not a whole number
x = "15";   // Illegal: cannot convert from a string to a number

Python also uses indentation to delimit code blocks, while the Java compiler uses {} to define code blocks and ; to terminate statements.

Data types in Java

See java-primitive-and-reference-types for the full primitive-vs-reference-types table. In short: Java distinguishes primitive types (built-in, fixed representations like int and boolean) from reference types — everything else, i.e. classes (including String and arrays).

Scope

A variable’s scope is where it can be used. In Java, a variable’s scope ends at the end of the block in which it’s declared. Python has no such rule, so the same code behaves differently in the two languages:

# z does not exist
if 5 > 4:
    z = 2
else:
    z = 3
print(z)          # This works!
if (5 > 4) {
    int z = 2;
} else {
    int z = 3;
}
System.out.println(z);   // This does not!

Question. What happens when this executes?

public static void main(String[] args) {
    if (5 > 4) {
        int z = 2;
    } else {
        int z = 3;
    }
    System.out.println(z);
}

It never executes — it’s a compile error: z is declared inside the if/else blocks, so it’s out of scope by the time System.out.println(z) is reached.

Answer. Declare the variable inside the same (or a higher) block as the print — hoist the declaration out and leave only the assignments in the branches:

public static void main(String[] args) {
    int z;
    if (5 > 4) {
        z = 2;
    } else {
        z = 3;
    }
    System.out.println(z);
}

Control flow: sequence, selection, and iteration

Sequence

  1. Each line must end with a semicolon (;).
  2. Declarations must come before other assignments.
  3. Instructions are executed sequentially.
public static void main(String[] args) {
    int x = 1;
    int y = 2;
    int z = x + y;
    System.out.println(z);
}

Methods are Java’s equivalent of Python functions — but all code must live inside a class:

def add_two_numbers(num1, num2):
    result = num1 + num2
    return result
class Arithmetic {           // All code must be inside a class.
    int add_two_numbers(int num1, int num2) {
        int result = num1 + num2;
        return result;
    }
}

Calling a method looks the same as calling a Python function: add_two_numbers(10, 20).

The Java method here keeps the Python name unchanged. Java’s own convention, used everywhere else in the course (see csse2002-diagram-notation §16), would be addTwoNumbers.

Selection: if and switch

if and switch are the same shape of control flow, so one diagram covers both:

Figure 2: Selection as a flowchart: one test fans out into mutually exclusive branches that all rejoin at a single point. The same diagram describes the if-chain and the switch. The selector x, the guards and the assignments are those of the month code below, with one branch box per named outcome.

The if chain:

String month;
if (x == 1) {
    month = "Jan";
} else if (x == 2) {
    month = "Feb";
} ... {
    month = "Dec";
} else {
    month = "Unknown";
}

The same thing as a switch. This is the arrow form (case … ->), not the old colon-and-break form. An arrow case takes a block and does not fall through, so no break is needed:

String month;
switch (x) {
    case 1 -> {
        month = "Jan";
    }
    case 2 -> {
        month = "Feb";
    }
    ...
    default -> {
        month = "Unknown";
    }
}

Exercise. Write a method printGrade that takes the mark of a student and determines the grade:

Mark Grade Description
83.00 – 100.00 High Distinction
73.00 – 82.99 Distinction
63.00 – 72.99 Credit
50.00 – 62.99 Pass
0.00 – 49.99 Fail

Iteration: while and for loops

Every counting loop has three moving parts:

  • Initialiser — initialise a counter variable.
  • Test/condition — check whether the counter has reached a condition.
  • Update — increment or decrement the counter.

Figure 3: The while loop’s control flow: the test is evaluated before each pass, and the update at the end of the body feeds the back-edge. The initialiser is orange, the test green and the update purple.

In a while loop the three parts are scattered across three lines:

int i = 0;              // initialiser
while (i < 10) {        // test
    System.out.println(i);
    i++;                // update
}
i = 0
while i < 10:
    print(i)
    i += 1

A for loop bundles all three into the loop header — the same three fragments, in the same order, separated by semicolons:

for (int i = 0; i < 10; i++) {
    System.out.println(i);
}
for i in range(10):
    print(i)

Exercise. A factorial of a number \(n\), written \(n!\), is the product of all numbers less than or equal to \(n\):

\[n! = n \times (n-1) \times (n-2) \times \cdots \times 2 \times 1 = \prod_{k=1}^{n} k\]

with \(0! = 1\), \(1! = 1\), \(2! = 2 \times 1 = 2\), \(3! = 3 \times 2 \times 1 = 6\). Write a method factorial that calculates the factorial of its input.

Exercise. For all positive integers it holds that \(n! = n \times (n-1)!\). Write an equivalent factorialRec method that uses recursion to calculate the result.

Java arithmetic

+, - and * work the same way as Python, except in a very special case.

Division is where the two languages diverge. Java has no // operator; instead, / is integer division whenever both operands are integers, and floating-point division as soon as either operand is a floating-point value:

Python Result Java Result
3 / 2 1.5 3 / 2 1
3 // 2 1 (no // operator) —
3 / 2.0 1.5 3 / 2.0 1.5
3.0 / 2 1.5 3.0 / 2 1.5
3.0 / 2.0 1.5 3.0 / 2.0 1.5

Comparison operators are identical in spelling to Python’s — x < y, x <= y, x > y, x >= y, x == y, x != y. One caveat applies to == alone: this holds for primitive types. On reference types, == compares object identity, not contents. The equality section of 2026-02-26-java-basics-part-02-collections-and-strings covers this.

Logical operators have the same semantics but different syntax:

Python Java
x and y x && y
x or y x || y
not x !x

Augmented assignment and increment/decrement:

Python Java
x += y x += y
x -= y x -= y
x += 1 x++
x -= 1 x--

Summary

  • The entry point for all Java programs is the main method: public static void main(String[] args).
  • Java is a compiled and statically typed language, compared to Python.
  • Most arithmetic operations in Java function identically to Python.
  • The same core principles of sequence, selection, and iteration apply to Java, but the syntax is different.

Reminders

  • Your first Ed Lessons exercise is due by 1pm next Wednesday.
  • Applied and practical classes start next week (Week 2).

Tasks this week:

Java Basics Part 02 - Collections and Strings

See csse2002 for staff, assessment, and course logistics. This is the week’s recorded lecture, a “Tasks this week” item in 2026-02-26-course-overview-and-java-basics. It goes alongside the live Lecture 1. The stack/heap material here is picked up again in the Week 3 applied class, week3-tutorial-stack-heap-and-class-design.

Outline

  • Java’s memory model: stack vs heap
  • Arrays and their limitations
  • Strings: indexing, substrings, equality, immutability
  • The Stack, List, Set, and Map collections

Java’s memory model

Runtime memory (the memory of the program while it’s running) splits into:

  • The stack — local variables and method parameters.
  • The heap — values with a dynamic size (objects and shared data).

Worked example: stack frames

public class StackHeap {
    public static void main(String[] args) {
        double hourlyRate = 54.0;
        int hoursWorked = 16;

        double salary = calculateSal(hourlyRate, hoursWorked);

        printSalary(salary);
    }
    public static double calculateSal(double hourlyRate, int hoursWorked) {
        return hourlyRate * hoursWorked;
    }
    public static void printSalary(double sal) {
        System.out.println("Salary: " + sal);
    }
}

The call stack, one frame at a time:

Figure 4: The call stack for the salary example at three moments. Each method call gets its own frame holding its parameters and locals; frames are pushed on top and popped in the reverse order (last in, first out), so calculateSal is gone by the time printSalary is pushed. The main frame is dark teal, calculateSal blue and printSalary orange; the open-topped container is the stack.

main pushes a frame holding hourlyRate = 54.0, hoursWorked = 16 and a not-yet-assigned salary. Calling calculateSal pushes a new frame on top with its own copies of hourlyRate and hoursWorked; it computes 54.0 * 16 = 864.0 and returns, popping its frame and storing the result in main’s salary. main then calls printSalary, which pushes a frame holding sal = 864.0, prints Salary: 864.0, and pops.

Worked example: heap allocation

An array’s size isn’t known until runtime, so the array object can’t live in the frame — it goes on the heap, and the frame holds only a reference to it:

static float lastMark(int n) {
    float[] marks = new float[n];

    marks[0] = 75.5f;
    marks[n - 1] = 88.0f;

    return marks[n - 1];
}

Figure 5: Calling lastMark(5). n is a primitive, so its value sits in the frame; marks is a reference, so the frame holds only a pointer at a float[5] object on the heap. new float[n] zero-fills the array, and the two assignments mutate that heap object through the reference, leaving [75.5, 0.0, 0.0, 0.0, 88.0]. The teal arrow is the reference, the open-topped container is the stack and the rounded region is the heap; the orange callee frame sits over the teal main frame.

Java never clears heap memory when a method ends. It clears heap memory only when no references exist and the Garbage Collection decides to run.

Arrays

An array is an ordered, fixed-length, mutable sequence of homogeneous items — the closest Java equivalent to a Python list, except that a Python list (list1 = ["abc", 34, True, 40, "UQ"]) is neither fixed-length nor homogeneous.

int[] numbers = {1, 2, 3, 4, 5};
numbers.length;        // 5   -- a field, not a method call
numbers[0] = 0;        // OK  -- {0, 2, 3, 4, 5}
numbers[0] = "zero";   // illegal -- all elements must be the same type, int

Two ways to create one:

// Approach 01: array literal
float[] marks = {60.3f, 62f, 70.1f, 65.8f, 80.3f};

// Approach 02: allocate, then assign each index
float[] marks = new float[5];
marks[0] = 60.3f;
marks[1] = 62f;
marks[2] = 70.1f;
marks[3] = 65.8f;
marks[4] = 80.3f;

The f suffixes are needed. Without them, float[] marks = {60.3, 62, 70.1, 65.8, 80.3} does not compile: an unsuffixed 60.3 is a double, and Java will not narrow a double to a float implicitly. The heap example writes 75.5f / 88.0f the same way.

Querying. Valid indices run from 0 to length - 1:

float[] marks = {60.3f, 62f, 70.1f, 65.8f, 80.3f};
System.out.println(marks[3]);      // 65.8
System.out.println(marks[0]);      // 60.3
int len = marks.length;            // 5
System.out.println(marks[len]);    // ArrayIndexOutOfBoundsException -- index 5 doesn't exist

Iterating. An indexed for loop, or the enhanced for-each loop:

for (int i = 0; i < len; i++) {
    System.out.println(marks[i]);
}

for (float mark : marks) {
    System.out.println(mark);
}

The general shape of a for-each is for (ElementType name : collection) { … } — e.g. for (String name : people) { … }.

Try at home.

  • max(int[]) — takes an array of integers and returns the maximum value.
  • contains(int[], int) — returns true if the input array contains the input integer, false otherwise.
  • reverse(int[]) — returns a new array with the elements in reverse order.

Limitations of arrays

Arrays are not great for everything:

  • Fixed size at creation. You do not always know how much space you are going to need.
  • They do not automatically close gaps.

On the second point: removing an element leaves a hole, and closing it is work you have to do yourself:

Figure 6: Why arrays motivate collections: deleting an element leaves a hole, and closing it means shifting every later element left by hand — and the array is still the same length, so the trailing cell has to be given some value. The notation is the array convention of csse2002-diagram-notation §13: equal-width cells with no index row, a grey ghosted digit for a value being shifted out, ? for an unspecified value, and a purple curved arrow above the row for one shift-left step. After the last row, the trailing cell is filled with a sentinel -1.

Strings

A String is a sequence of characters. The running example:

String course = "Programming in the Large";

Laid out with indices, this is 24 characters long — indices 0–23:

P r o g r a m m i n g ␣ i n ␣ t h e ␣ L a r g e
index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
System.out.println(course.length());     // 24  -- length() is a method on String
System.out.println(course.charAt(0));    // P
System.out.println(course.charAt(11));   // (the space between "Programming" and "in")
System.out.println(course.charAt(23));   // e

The three charAt results are read off the index row above.

One asymmetry trips people up: an array uses the field marks.length, a String uses the method course.length().

substring(start, end) returns a substring with an inclusive start index and an exclusive end index. If the end argument is not specified, the substring runs to the end of the string.

System.out.println(course.substring(0, 11));  // Programming  -- index 11 (the space) is excluded
System.out.println(course.substring(19));     // Large

Equality and immutability

=, == and != mean different things depending on which kind of type they are applied to. This is the “for primitive types” caveat on == in 2026-02-26-course-overview-and-java-basics:

Primitive types Reference types
x = y make x store a copy of y’s value make x refer to the same object y refers to
x == y check if x stores the same value as y check if x refers to the same object as y
x != y check if the value stored in x is different to y check if x and y are referencing different objects
String name  = "Jack";
String name2 = "Jack";
String name3 = new String("Jack");

System.out.println(name == name2);        // true
System.out.println(name == name3);        // false

System.out.println(name.equals(name2));   // true
System.out.println(name.equals(name3));   // true

Object obj1 = new Object();
Object obj2 = new Object();
System.out.println(obj1.equals(obj2));    // false

Two literals with the same contents are == because of the string pool; a new String(...) opts out of the pool and allocates a distinct object, so it is != but still .equals(). Object’s own equals() is identity, so two fresh Objects are never equal.

Figure 7: Why name == name2 is true but name == name3 is false. Identical string literals are interned once in the string pool and shared; a new String(...) call allocates its own object outside the pool. .equals() compares contents and so is true for all three. Ellipses are variables, rounded regions are memory, and teal arrows are references.

String objects are immutable. A String cannot be changed. Reassigning

String name = "Jack";
name = "Jill";

does not edit the "Jack" object. It leaves "Jack" untouched in memory and repoints the name reference at a different object, "Jill". Immutability comes back as a design property in java-mutability.

The Collections framework

See java-collections-framework for the full Stack/List/Set/Map interface reference. The rest of this section works through a trace of each. All of these live in java.util.*.

Stack

Last In, First Out (LIFO):

Method Meaning
empty() Is this stack empty?
peek() Return the object at the top of the stack
pop() Remove the object at the top of the stack
push(obj) Put obj on the top of the stack

Assume letters is an empty stack:

letters.empty();       // true
letters.push("A");
letters.empty();       // false
letters.push("B");
letters.push("C");
letters.peek();        // "C"
letters.push("D");

letters.pop();         // "D"
letters.pop();         // "C"
letters.pop();         // "B"
letters.pop();         // "A"
letters.pop();         // EmptyStackException

Creating a stack (must import the java.util.Stack package):

Stack<Type> stacks = new Stack<>();

Stack<Integer> stacks = new Stack<>();   // Integer type stack
Stack<String>  stacks = new Stack<>();   // String type stack
Stack<Cat>     stacks = new Stack<>();   // Cat type stack

Collections only store objects, so Stack<int> and Stack<double> are illegal. Java has a class for each primitive type: Boolean, Byte, Character, Double, Float, Integer, Long, Short (see java-primitive-and-reference-types).

Exercise. Implement a method int sum(Stack) that returns the sum of all integers in the given stack.

List

Lists hold items in sequential order, much like an array, but:

  • Grow and shrink automatically.
  • No fixed size limit.
  • Insert an item anywhere in the list.
  • Remove an item anywhere in the list.
  • Check if an item is in the list.
  • Index from zero, start of list.

List is an interface, not a particular implementation — you can declare a type as a list (List<String> xs), but you cannot create a list instance (new List<>() is illegal). Popular implementations:

  • LinkedList<String> — better for operations that modify the middle of the list.
  • ArrayList<String> — better for random access.

A trace, with the state after each line:

List<String> courses = new ArrayList<>();
courses.add("CSSE1001");     // [CSSE1001]
courses.add("DECO3801");     // [CSSE1001, DECO3801]
courses.get(0);              // "CSSE1001"
courses.add(1, "CSSE2310");  // [CSSE1001, CSSE2310, DECO3801]
courses.add(1, "CSSE2002");  // [CSSE1001, CSSE2002, CSSE2310, DECO3801]
courses.remove(2);           // removes and returns "CSSE2310"
                             // [CSSE1001, CSSE2002, DECO3801]
Noteremove(int) removes by index

remove(int) removes by index, and index 2 at that moment holds "CSSE2310". So courses.remove(2) returns "CSSE2310", not "CSSE2002": CSSE2002 survives at index 1 and CSSE2310 is gone.

The reason add(1, …) twice does not put both new entries at index 1 is that every insertion renumbers everything above it — the same shift work the array section did by hand, done for you:

Figure 8: courses.remove(2) on the courses ArrayList, before and after. Everything above the removed index slides down one and the list shrinks — which is exactly the gap-closing the raw array could not do. The list is drawn with index 0 at the bottom, growing upward: indices on the left, values in green on the right, and the variable name beneath.

Set

Sets store unique items (no duplicates). You can iterate over the set (don’t assume ordering), add an item, remove an item, and check if an item is in the set. add returns a boolean saying whether the set actually changed:

Set<String> farm = new HashSet<>();
farm.add("Fox");                      // true
farm.add("Farmer");                   // true
farm.add("Chicken");                  // true
farm.add("Fox");                      // false -- already present, set unchanged
farm.add("Grain");                    // true
System.out.println(farm.size());      // 4

Implementations: TreeSet<E> (E must implement Comparable, e.g. String) and HashSet<E> (E must have sensible hashCode()/equals()).

Map

Maps store key → value pairs (similar to a Python dictionary). You need to specify a type for each: Map<Integer, String> is Integer keys mapping to String values, and the value type can itself be a collection, e.g. Map<String, ArrayList<String>>.

Map<String, Integer> farm = new HashMap<>();
farm.put("Fox", 5);
farm.put("Farmer", 10);
farm.put("Chicken", 0);
farm.get("Farmer");                          // 10
farm.put("Fox", 18);                         // key already present -> value overwritten
farm.put("Grain", 15);
farm.put("Grain", farm.get("Grain") + 5);    // read-modify-write: Grain -> 20

Final contents: Fox → 18, Farmer → 10, Chicken → 0, Grain → 20. A HashMap has no meaningful iteration order, so don’t read anything into the order the entries are listed in.

Implementations: TreeMap<K,V> (K must implement Comparable) and HashMap<K,V> (K must have sensible hashCode()/equals()).

The hashCode/equals contract

HashSet<E> needs E, and HashMap<K,V> needs K, to have sensible hashCode() and equals() methods:

  1. x.equals(y) \(\iff\) y.equals(x) (symmetric).
  2. x.equals(y) \(\implies\) x.hashCode() == y.hashCode().

A hashCode() returns an integer value generated by a hashing algorithm for an object:

String name = "Thilina";
System.out.println(name.hashCode());   // 318621125

Week 2

Object Oriented Programming I

See csse2002 for staff, assessment, and course logistics.

Outline

  1. Objects, Classes, & Object-Oriented Programming
  2. Encapsulation
  3. Inheritance
  4. Abstraction
  5. Polymorphism (Week 3 — java-polymorphism)

Why OOP?

The case for objects rests on one running example grown in four stages: a bank, written first with nothing but static fields and static methods, then rewritten with objects. Watching what breaks at each stage is the argument for OOP. The bank carries only that argument. Inheritance has its own example, Employee, and abstraction another, PaymentProcessor/Payment. Polymorphism is left whole to Week 3.

Stage 1 — one global balance

public class BankBasic {
    static double bankBalance = 0; // Single balance for the entire bank

    public static void deposit(double amount) {
        bankBalance += amount;
    }

    public static void withdraw(double amount) {
        if (bankBalance >= amount) {
            bankBalance -= amount;
        } else {
            System.out.println("Insufficient funds.");
        }
    }

    public static void checkBalance() {
        System.out.println("Bank Balance: $" + bankBalance);
    }

    public static void main(String[] args) {
        deposit(5000);
        withdraw(2000);
        checkBalance(); // Output: Bank Balance: $3000.0
    }
}

The listing has two kinds of thing in it: the field bankBalance is a variable, x, and the three methods are functions of it, f(x). That framing — free variables on one side, free functions on the other — is the shape the next three stages keep running into.

There is one balance for the entire bank. There is no way to represent a second account, let alone a second customer.

Stage 2 — parallel arrays of accounts

public class BankWithAccounts {
    static final int MAX_ACCOUNTS = 10;
    static String[] accountNumbers = new String[MAX_ACCOUNTS];
    static double[] balances = new double[MAX_ACCOUNTS];
    static int accountCount = 0;

    public static void createAccount(String accountNumber, double initialBalance) { ... }
    public static int findAccountIndex(String accountNumber) { ... }
    public static void deposit(String accountNumber, double amount) { ... }
    public static void withdraw(String accountNumber, double amount) { ... }
    public static void checkBalance(String accountNumber) { ... }

    public static void main(String[] args) {
        createAccount("A123", 1000);
        createAccount("B456", 2000);

        deposit("A123", 500);
        withdraw("B456", 300);

        checkBalance("A123"); // Expected: Balance for A123: $1500.0
        checkBalance("B456"); // Expected: Balance for B456: $1700.0
    }
}

Every piece of account data needs its own array, and the arrays are held together only by agreeing on the index. accountCount has to be maintained by hand, and a findAccountIndex helper now stands between an account number and the position it names.

Stage 3 — parallel arrays of account holders too

public class BankWithHolders {
    static final int MAX_ACCOUNTS = 10;

    // Account Holder Data
    static String[] holderIds   = new String[MAX_ACCOUNTS];
    static String[] holderNames = new String[MAX_ACCOUNTS];
    static int holderCount = 0;

    // Account Data
    static String[] accountNumbers  = new String[MAX_ACCOUNTS];
    static double[] balances        = new double[MAX_ACCOUNTS];
    static String[] linkedHolderIds = new String[MAX_ACCOUNTS]; // Link accounts to holders
    static int accountCount = 0;

    public static void createAccountHolder(String id, String name) { ... }
    public static int findHolderIndex(String holderId) { ... }
    public static void createAccount(String accountNumber, double initialBalance,
                                     String holderId) { ... }
    public static int findAccountIndex(String accountNumber) { ... }
    public static void deposit(String accountNumber, double amount) { ... }
    public static void withdraw(String accountNumber, double amount) { ... }
    public static void checkBalance(String accountNumber) { ... }

    public static void main(String[] args) {
        createAccountHolder("001", "Jack Johnson");
        createAccountHolder("002", "Jill Smith");

        createAccount("A123", 1000, "001");
        createAccount("B456", 2000, "002");

        deposit("A123", 500);
        withdraw("B456", 300);

        checkBalance("A123"); // Output: Balance for Jack Johnson: $1500.0
        checkBalance("B456"); // Output: Balance for Jill Smith: $1700.0
    }
}

Adding a second kind of thing (holders) doubles the bookkeeping: two more parallel arrays, a second count, a second index-finder, and a third array (linkedHolderIds) whose only job is to remember which holder each account belongs to. Nothing in the language enforces that any of these arrays stay in step.

What that program actually looks like

Figure 9: The procedural picture after the three bank stages: every function and every variable lives in one flat frame, and any function may call any other. The boxes are functions, the ellipses are variables and the six arrows are calls.

The variables a, c and x belong to nobody. Any function may read or write any of them, and the call graph is free to cross in any direction. Nothing in the picture says which function is allowed to touch which variable — that knowledge lives only in the programmer’s head.

The fix: group each variable with the functions that act on it

Figure 10: Three self-contained units, each owning its own data and the functions that operate on it. Each unit has its own colour. This is a fresh illustration, not a literal regrouping of the procedural figure: f6 is new, f’ and f5 are gone, and f2 and f4 have different parameter lists.

This is the whole idea: instead of scattering related data across parallel arrays and free functions, bundle a variable and the functions that act on it into a single unit — a class. The second figure uses a fresh cast of functions, so don’t try to match the two figures member for member. Bundling the data and the functions that operate on the data into a single unit restricts direct access to some of an object’s components and can prevent the accidental modification of data.

Stage 4 — the same bank, with objects

The bank is then rewritten as four classes. Arrays do not disappear — each set of parallel arrays collapses into a single array of objects (BankAccount[], AccountHolder[]) held privately inside Bank, and the per-thing data that used to be spread across those arrays becomes fields on the object:

public class AccountHolder {
    private String id;
    private String name;
    private String contactInfo;

    public AccountHolder(String id, String name, String contactInfo) {
        this.id = id;
        this.name = name;
        this.contactInfo = contactInfo;
    }
    public String getId() { return id; }
    public String getName() { return name; }
    public String getContactInfo() { return contactInfo; }
}

public class BankAccount {
    private String accountNumber;
    private double balance;
    private AccountHolder accountHolder; // Association with AccountHolder

    public BankAccount(String accountNumber, double initialBalance,
                       AccountHolder accountHolder) { ... }

    public void deposit(double amount) { balance += amount; }
    public void withdraw(double amount) { ... }
    public double checkBalance() { return balance; }
    public String getAccountNumber() { return accountNumber; }
    public AccountHolder getAccountHolder() { return accountHolder; }
}

public class Bank {
    private static final int MAX_ACCOUNTS = 10;
    private BankAccount[] accounts = new BankAccount[MAX_ACCOUNTS];
    private int accountCount = 0;
    private AccountHolder[] accountHolders = new AccountHolder[MAX_ACCOUNTS];
    private int holderCount = 0;

    public void createAccountHolder(String id, String name, String contactInfo) { ... }
    private AccountHolder findAccountHolder(String id) { ... }
    public void createAccount(String accountNumber, double initialBalance,
                              String holderId) { ... }
    private BankAccount findAccount(String accountNumber) { ... }
    public void deposit(String accountNumber, double amount) { ... }
    public void withdraw(String accountNumber, double amount) { ... }
    public void checkBalance(String accountNumber) { ... }
    public void displayAllAccounts() { ... }
}

and the driver becomes a script against one bank object:

public class OOPBanking {
    public static void main(String[] args) {
        Bank bank = new Bank();

        // Creating account holders
        bank.createAccountHolder("001", "Jack Johnson", "jack@uq.com.au");
        bank.createAccountHolder("002", "Jill Smith", "jill@uq.com.au");

        // Creating accounts linked to account holders
        bank.createAccount("A123", 1000, "001");
        bank.createAccount("B456", 2000, "002");

        // Performing transactions
        bank.deposit("A123", 500);
        bank.withdraw("B456", 300);

        // Checking balances
        bank.checkBalance("A123"); // Output: Balance for Jack Johnson: $1500.0
        bank.checkBalance("B456"); // Output: Balance for Jill Smith: $1700.0

        // Displaying all accounts
        bank.displayAllAccounts();
    }
}

Three things changed, and they are the payoff:

  • Every field is now private — the arrays that used to be static and open to the world are hidden inside Bank.
  • findAccountHolder and findAccount are private: index bookkeeping became an internal detail rather than part of the public surface.
  • The “which holder owns this account” link is a reference field on BankAccount (private AccountHolder accountHolder), not a third parallel array. This kind of link is an association.

The four pillars of object orientation

  1. Encapsulation — see java-encapsulation
  2. Inheritance — see java-inheritance
  3. Abstraction — see java-abstraction
  4. Polymorphism — Week 3 (java-polymorphism, 2026-03-12-object-oriented-programming-ii)

The mechanics of each pillar

The mechanics under each pillar are written up in the concept notes:

Topic Note
classes vs objects, constructors and the default constructor java-encapsulation
access modifiers (private, public, protected, default) java-encapsulation
getters and setters java-encapsulation
the static keyword — class variables and static methods java-encapsulation
class invariants java-encapsulation
method signatures and why they must be unique java-encapsulation
extends, super, method overriding java-inheritance
interfaces and abstract classes java-abstraction

Two items are homework:

Preconditions and postconditions come in Week 3 — see java-specification.

Java Basics Practical - Palindromes

Practical exercises for week 2. IntelliJ IDEA is the course’s supported IDE (see the install guide on Blackboard). The Java 21 API docs cover the String class in java.lang, which is needed below.

On the HTML site, fill in each blank with your answer (as a quoted string, e.g. "true"), 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 — Palindromes

A palindrome reads the same forwards and backwards, e.g. "AaaA", "madamimadam", "racecar".

Implement four methods, all with the signature public static boolean isPalindromeN(String word) (for \(N=1..4\)), each using a different technique:

  1. isPalindrome1 — a for loop.
  2. isPalindrome2 — a while loop.
  3. isPalindrome3 — recursive, with no helper methods.
  4. isPalindrome4 — recursive, using a private helper method.

All four should agree on at least these cases. What does each return?

isPalindromeN("AaA") →

isPalindromeN("A") →

isPalindromeN("") →

isPalindromeN("Abbb") →

All four methods do the same comparisons — first character against last, second against second-last, and so on — but they keep track of where they are up to in two structurally different ways:

Figure 11: The two reductions behind the four methods. (a) isPalindrome1, isPalindrome2 and isPalindrome4 leave the string alone and move an index i inwards, comparing charAt(i) with charAt(len - i - 1) and stopping once i reaches len / 2 - which is why the middle character of an odd-length word is never examined. (b) isPalindrome3 keeps no index at all: it compares the two ends, then recurses on substring(1, length() - 1), so the string itself shrinks by two characters per call until length() < 2 is the base case. Characters no longer in the live window are greyed out; the teal double arrows are comparisons.

Task 0 — isPalindrome1 (for loop):

public static boolean isPalindrome1(String word) {
    int len = word.length();
    for (int i = 0; i < len / 2; i++) {
        if (word.charAt(i) != word.charAt(len - i - 1)) {
            return false;
        }
    }
    return true;
}

Task 1 — isPalindrome2 (while loop):

public static boolean isPalindrome2(String word) {
    int len = word.length();
    int i = 0;
    while (i < len / 2) {
        if (word.charAt(i) != word.charAt(len - i - 1)) {
            return false;
        }
        i++;
    }
    return true;
}

Task 2 — isPalindrome3 (recursive, no helper methods). To write any recursive method, identify the base case (the input is trivially solvable — obviously a palindrome or obviously not) and the recursive case (which must reduce the problem to a smaller one, moving towards the base case). Applied here: if \(xy \ldots yx\) is a palindrome, then \(y \ldots y\) must be too — and substring is how you extract \(y \ldots y\) (panel (b) of Figure 11).

public static boolean isPalindrome3(String word) {
    if (word.length() < 2) {
        return true; // base case
    }
    if (word.charAt(0) != word.charAt(word.length() - 1)) {
        return false; // base case
    }
    return isPalindrome3(word.substring(1, word.length() - 1)); // recursive step
}

Task 3 — isPalindrome4 (recursive, with a private helper). The helper carries the index, so this is panel (a)’s reduction driven by recursion rather than by a loop. Because the index does the work, this version never calls substring, so unlike isPalindrome3 it allocates no new String on each step.

public static boolean isPalindrome4(String word) {
    return helper(word, 0);
}

private static boolean helper(String word, int i) {
    if (i >= word.length() / 2) {
        return true; // base case
    }
    if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
        return false; // base case
    }
    return helper(word, i + 1); // recursive step
}

All four agree on the required test cases: "AaA" → true, "A" → true, "" → true, "Abbb" → false.

Code review

A paired activity, not a gradable exercise: swap solutions with a partner, and for each other’s code —

  • Understand it, and ask questions about anything unclear.
  • Check correctness against the test cases above (and a few of your own).
  • Check it follows the course style guide.
  • Discuss/suggest improvements if you find issues.

Then discuss which of the four isPalindromeN techniques you each preferred, and why.

Java Basics Applied Class

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 12: 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 12 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 13: 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 13 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.

Week 3

Object Oriented Programming II

See csse2002 for course logistics. Continues 2026-03-05-object-oriented-programming-i.

The week has two parts:

  1. Object Oriented Programming II: interface vs abstract class, encapsulation revision, mutability, polymorphism, casting.
  2. Specification: Javadoc, restrictiveness, generality, clarity, formality, contracts, defensive programming.

Three items are homework (self-study): primitive casting, defensive copying, and how a subclass can introduce mutability.

Recap: the four (five) pillars

Week 2 covered objects/classes/OOP, encapsulation, inheritance and abstraction. This week adds polymorphism as the fifth, and goes back over encapsulation and the interface/abstract-class comparison in more depth.

Interface vs abstract class

Week 2 left this comparison as homework. The full treatment is in java-abstraction. In short:

  • An interface defines a capability or contract — Flyable, Runnable, Payable. Unrelated classes can share it: Bird implements Flyable and Plane implements Flyable.
  • An abstract class defines a shared base implementation — common behaviour that subclasses inherit rather than restate.

In code, the interface carries nothing but a signature. The abstract class carries a finished method alongside an unfinished one.

public interface PaymentProcessor {
    void processPayment(double amount);
}
public abstract class Payment {
    public void validateTransaction() {
        System.out.println("Validating transaction...");
    }

    abstract void processPayment(double amount);
}

The course’s running Animal example has the same shape. eat() is inherited as-is, and makeSound() must be supplied by each subclass:

abstract class Animal {
    public void eat() {
        System.out.println("Animal is eating");
    }

    public abstract void makeSound();
}

class Dog extends Animal {
    @Override
    public void makeSound() { System.out.println("Dog barks"); }
}

class Cat extends Animal {
    @Override
    public void makeSound() { System.out.println("Cat Meows"); }
}

Figure 14: The abstract-class case: shared behaviour (eat()) lives in Animal, while each subclass supplies its own makeSound(). One connector joins both subclasses to the parent, with a single arrowhead into Animal.

The two combine. A class has at most one superclass, as many interfaces as you like.

class Dog  extends Animal implements Runnable, Swimmable
class Duck extends Animal implements Flyable,  Swimmable

Revising encapsulation

Person from java-encapsulation again: private fields with public getters. One field matters for the next section:

public class Person {
    private String name;
    private int age;
    private String email;
    private String[] phoneNumber;   // <- a mutable field

    public Person(String name, int age, String email, String[] phoneNumber) {
        this.name = name;
        this.age = age;
        this.email = email;
        this.phoneNumber = phoneNumber;
    }

    public String getName()          { return name; }
    public int getAge()              { return age; }
    public String getEmail()         { return email; }
    public String[] getPhoneNumber() { return phoneNumber; }
}

The array field is the case where private and final together are still not enough.

Mutable vs immutable classes

See java-mutability — mutable and immutable class design, the arrays/lists gotcha where final protects only the reference, and defensive copying.

Polymorphism

See java-polymorphism — compile-time (overloading), runtime (overriding / dynamic method dispatch), and subtype polymorphism.

Casting

See java-casting — primitive widening/narrowing, and reference upcasting/downcasting. Practised in week4-tutorial-method-dispatch-and-casting.

Worked: what is the parent of Student?

What is the parent of class Student?

public class Student {
    public void study() {
        System.out.println("CSSE2002");
    }
}

Object. A class with no extends clause still has a superclass. The class hierarchy has Object at the root of everything.

Specification

See java-specification — Javadoc, restrictiveness, generality, clarity, formality, contracts, and defensive programming.

Key takeaways

Object oriented programming:

  • Encapsulation protects implementation details and prevents direct access to internal state.
  • Inheritance lets a class reuse behaviour from another class — but can expose the internal implementation details of a superclass.
  • Abstraction hides complex implementation detail: the user knows what it does, not how it works internally.
  • Polymorphism lets objects be treated as their common type, and lets different objects respond differently to the same method call.

OOP helps build flexible, reusable, and maintainable software by organizing code around objects and behaviour.

Specification:

  • A specification describes the contract between a method and its client.
  • It explains what the method does, not how it is implemented.
  • A good specification clearly states preconditions (true before the call), postconditions (true after a successful call) and side effects (any other change the method makes to the system).
  • Clear specifications make code easier to understand, use and maintain.

Java Classes - Point Line Polynomial

Practical exercises for week 3, building up a small set of geometry classes (Point, then Line on top of it, then an independent Polynomial) to practice java-encapsulation and java-mutability (note that movePoint/flipPoint/scale-style methods return a new object rather than mutating this).

The sheet opens with a habit it then assumes for the rest of semester:

Note on testing. From now on, whenever we ask you to write a class, you should also write a simple main method to test its functionality. This does not need to be in the same class (not every class needs a main method — testing class Foo and class Bar in class Test is fine).

On the HTML site, fill in each blank with your answer (as a quoted string, e.g. "5.0"), 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).

Figure 15: The worked plane the first three questions build against, combining three separate plots from the week 3 practical solutions: the two points (2,3) and (4,1) of p1, the line joining them of p2, and the midpoint of p7 labelled with the formula the sheet prints. The midpoint of this particular line is (3,2).

Question 1 — Points

Write a Point class representing an x,y-coordinate on a Cartesian plane. A Point stores two floats, one for each coordinate, with:

  • Point(float x, float y) and a default Point() (both 0).
  • float getX()/float getY().
  • Point movePoint(float deltaX, float deltaY) — returns a new Point at (getX() + deltaX, getY() + deltaY). The sheet emphasises: this method should not modify the Point it is called on.
  • static double distance(Point p, Point q) — Euclidean distance between \(p = (x_1, y_1)\) and \(q = (x_2, y_2)\):

\[d\big((x_1,y_1),(x_2,y_2)\big) = \sqrt{(x_1-x_2)^2 + (y_1-y_2)^2}\]

If p1 = new Point() and p2 = p1.movePoint(4, 5), what does p2 print (assuming a toString of "(" + x + ", " + y + ")")?

public class Point {
    private float x;
    private float y;

    public Point() {
        this(0, 0);
    }

    public Point(float x, float y) {
        this.x = x;
        this.y = y;
    }

    public float getX() { return this.x; }
    public float getY() { return this.y; }

    public Point movePoint(float deltaX, float deltaY) {
        return new Point(this.x + deltaX, this.y + deltaY);
    }

    public static double distance(Point p, Point q) {
        double x = p.x - q.x;
        double y = p.y - q.y;
        return Math.sqrt(x * x + y * y);
    }

    @Override
    public String toString() {
        return "(" + x + ", " + y + ")";
    }
}

Three details in the model answer worth copying:

  • The default constructor is written this(0, 0) — constructor chaining — rather than repeating the two assignments. One place initialises the fields.
  • movePoint deliberately returns a new Point rather than mutating this, so p1 is left at (0.0, 0.0) and p2 is (4.0, 5.0).
  • distance is static and reads p.x and q.x directly, not through getX(). That compiles because private in Java is per-class, not per-object: any Point method can reach any other Point’s private fields.

Question 2 — Lines

Write a Line class storing a start Point, an end Point, and the (precomputed) double length between them, with:

  • Line(Point start, Point end) — also stores the distance between the two points — and a default Line() (both ends at the origin, length 0).
  • getStart()/getEnd()/getLength().
  • void moveStart(float deltaX, float deltaY) / void moveEnd(float deltaX, float deltaY) — mutator methods that move the line’s start/end by the given values.

For a Line from (0, 0) to (3, 4), what is getLength()?

public class Line {
    private Point start;
    private Point end;
    private double length;

    public Line() {
        this.start = new Point();
        this.end = new Point();
        this.length = 0;
    }

    public Line(Point start, Point end) {
        this.start = start;
        this.end = end;
        this.length = Point.distance(start, end);
    }

    public Point getStart() { return start; }
    public Point getEnd() { return end; }
    public double getLength() { return length; }

    public void moveStart(float deltaX, float deltaY) {
        start = start.movePoint(deltaX, deltaY);
        length = Point.distance(start, end);
    }

    public void moveEnd(float deltaX, float deltaY) {
        end = end.movePoint(deltaX, deltaY);
        length = Point.distance(start, end);
    }

    @Override
    public String toString() {
        return start.toString() + " " + end.toString() + " " + this.getLength();
    }
}

(0,0) to (3,4) is a 3-4-5 right triangle, so the length is exactly 5.0.

Note the two designs sitting side by side, deliberately: Point.movePoint is immutable (returns a new object, void nowhere in sight) while Line.moveStart/moveEnd are mutators (void, changing this). moveStart is written on top of the immutable one — start = start.movePoint(...) builds a fresh Point and rebinds the field to it, rather than reaching into the old Point and editing it.

length is a derived field: it is not independent state, it is a cached function of start and end. That is why every method that touches an endpoint has to recompute it on the next line. Storing it at all is a choice the sheet makes for you (the question says a Line stores “a double representing the length”), and the recomputation is the price — see java-encapsulation on keeping an object’s fields consistent with each other.

Question 3 — Testing and toString

Unless overridden, printing an object prints its class name and memory location, e.g. Point@30f39991 — the class name Point plus the location in memory 30f39991. Writing a toString() that returns a String overrides that default when a class instance is converted to a string, and makes testing by eye possible at all.

The sheet’s own reason for doing this now rather than later: “Now is a good opportunity to test your program, if you haven’t already. It is a bad idea to write too much code before checking that it works.”

Point p1 = new Point();
Point p2 = p1.movePoint(4, 5);

System.out.println(p1); // (0.0, 0.0)
System.out.println(p2); // (4.0, 5.0)

Line’s version delegates to Point’s rather than reaching for start.getX() and friends:

@Override
public String toString() {
    return start.toString() + " " + end.toString() + " " + this.getLength();
}

Question 4 — Additional methods

Add to Point:

  • Line createLine(Point end) — a Line with this as the start and end as the end.
  • Point flipPoint() — returns a new object with the sign of both coordinates changed, e.g. \((-1, 2)\) becomes \((1, -2)\).

Add to Line:

  • Point middle() — the midpoint of the start and end, at \(\left(\frac{x_1+x_2}{2}, \frac{y_1+y_2}{2}\right)\).
  • Line flipLine() — a new Line with both endpoints flipped as above.

What does new Point(-1, 2).flipPoint() print?

Figure 16: What flipping means geometrically, redrawing the two plots the week 3 practical solutions use to define it (p6 for the point, p7 for the line) side by side in one frame. Left: flipPoint negates both coordinates, so (-1,2) lands at (1,-2) - a 180-degree rotation about the origin, not a reflection in either axis. Right: flipLine is just that applied to both endpoints, sending the blue line (2,3)-(4,1) to the red line (-2,-3)-(-4,-1). The colours are the sheet’s.

On Point:

public Line createLine(Point end) {
    return new Line(this, end);
}

public Point flipPoint() {
    return new Point(x * -1, y * -1);
}

On Line:

public Point middle() {
    return new Point((start.getX() + end.getX()) / 2,
            (start.getY() + end.getY()) / 2);
}

public Line flipLine() {
    return new Line(start.flipPoint(), end.flipPoint());
}

Each of the four is a one-liner because the layer beneath it already exists: createLine hands this to a constructor, flipLine is flipPoint applied twice, middle is arithmetic on accessors. This is the payoff for having written Point properly first.

Note flipLine does not mutate — consistent with flipPoint and movePoint, and inconsistent with moveStart/moveEnd, which do. The class ends up with both conventions in it; the sheet does not reconcile them.

Question 5 — Polynomials (bonus)

A polynomial function specifies lines and curves on a Cartesian plane in terms of its coefficients:

Figure 17: The four example polynomials plotted in the week 3 practical solutions p8, redrawn with the sheet’s own colour coding and its full a + bx + cx^2 spellings alongside the collapsed forms. The point of the figure is that a straight line, a horizontal line and a parabola are all the same object here - only the three coefficients differ. The colour-keyed equation list is placed inside the figure rather than beside it as the sheet does.

In general a polynomial function has the form

\[f(x) = a_0 + a_1x + a_2x^2 + \dots + a_{n-1}x^{n-1} + a_nx^n\]

where \(a_0 \dots a_n\) are its coefficients. For this exercise it is restricted to \(f(x) = a + bx + cx^2\).

Write a Polynomial class represented by its coefficients, with constructors Polynomial() (giving \(f(x) = 0\)), Polynomial(float a), Polynomial(float a, float b), Polynomial(float a, float b, float c), plus:

  • float valueAt(float x) — the value of the polynomial at \(x\).
  • Polynomial add(Polynomial other) — a new Polynomial for \(f_1(x) + f_2(x) = (a_1 + a_2) + (b_1 + b_2)x + (c_1 + c_2)x^2\).

For \(f(x) = 1 + 2x\), what is \(f(3)\)?

\(f(3) = 1 + 2 \times 3 = 7\).

The model answer stores a float[] from the start, so it already solves the challenge below; the four “restricted” constructors are just convenience wrappers over one array:

import java.util.StringJoiner;

public class Polynomial {
    private final float[] coefficients;

    public Polynomial() { coefficients = new float[]{0}; }
    public Polynomial(float a) { coefficients = new float[]{a}; }
    public Polynomial(float a, float b) { coefficients = new float[]{a, b}; }
    public Polynomial(float a, float b, float c) { coefficients = new float[]{a, b, c}; }
    public Polynomial(float[] coefficients) { this.coefficients = coefficients; }

    private static float index(float[] coefficients, int index) {
        /* The value of coefficients with index greater than
         * the maximum index of the polynomial is 0. */
        if (index >= coefficients.length) {
            return 0;
        }
        return coefficients[index];
    }

    public Polynomial add(Polynomial other) {
        int max = Math.max(coefficients.length, other.coefficients.length);
        float[] newCoefficients = new float[max];
        for (int i = 0; i < max; i++) {
            newCoefficients[i] = index(coefficients, i)
                    + index(other.coefficients, i);
        }
        return new Polynomial(newCoefficients);
    }

    public float valueAt(float x) {
        float v = 0;
        float xpower = 1;
        for (int i = 0; i < coefficients.length; i++) {
            /* xpower = x^i */
            v += coefficients[i] * xpower;
            xpower *= x;
        }
        return v;
    }

    @Override
    public String toString() {
        StringJoiner builder = new StringJoiner(" + ");
        for (int i = 0; i < coefficients.length; i++) {
            builder.add(coefficients[i] + "x^" + i);
        }
        return builder.toString();
    }
}

Three things the model answer is doing on purpose:

  • private static float index(...) exists so add can read past the end of the shorter array without an if in the loop body — a coefficient that isn’t stored is \(0\). Without it, add would need a length check per term.
  • valueAt carries xpower along instead of calling Math.pow(x, i) each iteration: one multiply per term rather than a power computation per term. (Recognisably Horner-adjacent, though the sheet does not name it.)
  • coefficients is final, so a Polynomial cannot be re-pointed at a different coefficient array after construction — which is what lets add safely return a new instance rather than worrying about shared state. Note the Polynomial(float[]) constructor still stores the caller’s array by reference, so the contents are not protected; see java-mutability.

toString uses StringJoiner(" + "), which inserts the separator only between items — so a one-term polynomial prints without a trailing +.

Challenge — representing the unrestricted \(f(x) = a_0 + a_1x + \dots + a_nx^n\) for any \(n \geq 0\) needs no new code: valueAt, add and toString are all written against coefficients.length, and the Polynomial(float[]) constructor already accepts an array of any length.

Testing it end to end

The sheet’s own Main sweeps each polynomial across \(x \in [-10, 10)\) and prints the line, which is how you check Figure 17 by eye rather than by trust:

public class Main {
    private static void testPoints(Polynomial p) {
        for (int x = -10; x < 10; x++) {
            System.out.print(p.valueAt(x) + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Point p1 = new Point();
        Point p2 = p1.movePoint(4, 5);

        System.out.println(p1);
        System.out.println(p2);

        Line line = new Line(p1, p2);
        System.out.println(line);

        Polynomial acrossZero = new Polynomial();
        testPoints(acrossZero);

        Polynomial acrossTwo = new Polynomial(2);
        testPoints(acrossTwo);

        Polynomial diag = new Polynomial(1, 2);
        testPoints(diag);

        Polynomial slope = new Polynomial(2, -2);
        testPoints(slope);

        Polynomial parab = new Polynomial(1, 0, 0);
        testPoints(parab);

        System.out.println(parab);
        System.out.println(slope);
    }
}

Note new Polynomial(1, 0, 0) is named parab but is \(f(x) = 1\), a flat line — the coefficients are in ascending order (\(a\), then \(b\), then \(c\)), so the parabola would be new Polynomial(0, 0, 1). (That reading is mine, not the sheet’s; the sheet prints the listing without comment. It is a good illustration of why toString is worth writing: running this prints 1.0x^0 + 0.0x^1 + 0.0x^2 and the mistake is visible immediately.)

Stack Heap and Class Design

Applied class exercises for week 3, covering 2026-03-12-object-oriented-programming-ii and reinforcing java-mutability (why reference types behave differently from primitives when passed to methods). The class has two halves: sketching the runtime call stack and object heap to explain reference behaviour, and using that same “an object is a thing with fields” view to argue for a better class design.

On the HTML site, fill in each blank with your answer (as a quoted string, e.g. "1"), 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).

How to draw a stack/heap sketch

The sketches use a fixed vocabulary. Learn it before attempting the questions, because it is the form the answers are expected in:

  • a stack frame is the method’s name in bold above a two-column table, one row per local — parameters count as locals and get a row;
  • a primitive value is written straight into the value cell (3, 0, 1);
  • a reference is a filled dot in the value cell, with a black arrow to the object it names;
  • a heap array is a plain box holding the array literal, e.g. {3, 2, 3};
  • a heap object is a box with the class name in a bold header and one name/value row per field;
  • frames whose call has already returned are greyed out, and it is not necessary to include them at all;
  • frames are stacked with main at the top and each deeper call beneath it.

Two aliases pointing at one box is the whole point of the notation: it is what makes “the same object seen through two names” visible on paper.

The warm-up: aliasing an array

The whole exercise is motivated by a function whose return value surprises people:

static int[] reverse() {
    int[] first = {1, 2, 3};
    int[] second = first;

    int last = first[2];
    second[0] = last;
    second[1] = first[1];
    second[2] = first[0];

    return second;
}

This returns {3, 2, 3}, not {3, 2, 1}.

Figure 18: The stack and heap for the warm-up reverse() function. One stack frame, four rows, and a single heap array: first, second and the returned value are three names for one box, which is why writing through second is visible when read back through first. A filled dot with a black arrow is a reference; a primitive’s value is written in its cell.

int[] second = first; copies the reference, not the array. So there is exactly one array on the heap, and the three assignments all write into it:

step array afterwards
last = first[2] {1, 2, 3}, last == 3
second[0] = last {3, 2, 3}
second[1] = first[1] {3, 2, 3} (writes 2 over 2)
second[2] = first[0] {3, 2, 3} — first[0] is now 3, not the original 1

The last line is where the aliasing bites: by the time it runs, first[0] has already been overwritten. If second were an independent copy, the last line would read the untouched 1 and the function would return {3, 2, 1}, an actual reverse.

Question 1 — Tracing the call stack and heap

Understanding the runtime call stack and object heap clarifies unexpected behaviour of reference types. Consider:

class Counter {
    private int number;

    public Counter() { this.reset(); }
    public void increment(int amount) { this.number += amount; }
    public void increment() { this.number++; }
    public void reset() { this.number = 0; }
    public int getValue() { return this.number; }
}

class DebugMe {
    static void f(Counter counter, int param) {
        counter.increment();
        param++;
    }

    public static void main(String[] args) {
        Counter first = new Counter();
        int second = 0;
        f(first, second);
        System.out.println(first.getValue());
        System.out.println(second);
    }
}

Task 0 is to sketch the state of the call stack and heap just before f finishes executing; Task 1 is to say what main prints.

What does main print (first line, then second line)?

First line →

Second line →

Figure 19: Task 0’s answer: the state just before f returns. main sits above f; args and first hold references (dots) into the heap, second holds the primitive 0. first and counter point at the SAME Counter object, whose number field already reads 1. The increment frame is greyed because that call has already returned; such frames need not be drawn at all.

Read the answer straight off the picture:

  • first and counter are two references to one Counter object. counter.increment() inside f mutates that shared object, so the change is visible through first after f returns — first.getValue() prints 1.
  • param is an int, passed by value. param++ increments f’s own copy (the frame shows param at 1) and leaves main’s second at 0 — so the second line prints 0.

That is the general rule this class exists to fix in place: mutating an object through a reference parameter is visible to the caller; reassigning or incrementing a primitive parameter is not. (Reassigning a reference parameter — counter = new Counter() inside f — would likewise be invisible to main; Java passes the reference itself by value.)

args still gets a row and still points at a heap array, drawn {} because the program was run with no command-line arguments.

Question 2 — Designing a Vertex class

The Triangle class represents a triangle as a 2D array of coordinates: vertexes[0] is the three x-coordinates, vertexes[1] the three y-coordinates.

Figure 20: The triangle the exercise is about: vertices A, B, C with the interior angles alpha, beta, gamma and the sides a, b, c opposite them, beside the matrix form of the representation - one row of x-coordinates over one row of y-coordinates, which is exactly the double[][] the Triangle class stores.

The three-double constructor takes the side lengths \(a\), \(b\), \(c\) of Figure 20, not coordinates, and places the triangle in the plane for you:

public class Triangle {
    private double[][] vertexes;

    private static double square(double number) {
        return number * number;
    }

    public Triangle(double a, double b, double c) {
        double dividend = (square(a) - square(b) - square(c));
        double cx = dividend / (-2 * c);
        double cy = Math.sqrt(square(b) - square(cx));
        // the above just calculates the position of a third vertex
        // you do not need to understand it

        this.vertexes = new double[][]{
            // array of x-coordinates
            new double[]{0, c, cx},
            // array of y-coordinates
            new double[]{0, 0, cy}
        };
    }

    public Triangle(double[][] vertexes) {
        this.vertexes = vertexes;
    }

    private double distance(double x1, double x2, double y1, double y2) {
        return Math.sqrt(square(x1 - x2) + square(y1 - y2));
    }

    public double perimeter() {
        double x0 = vertexes[0][0];
        double x1 = vertexes[0][1];
        double x2 = vertexes[0][2];
        double y0 = vertexes[1][0];
        double y1 = vertexes[1][1];
        double y2 = vertexes[1][2];
        return distance(x0, y0, x1, y1) + distance(x1, y1, x2, y2)
                + distance(x2, y2, x0, y0);
    }

    public Triangle scale(double multiplier) {
        double[][] scaledUp = new double[2][3];
        for (int x = 0; x < 2; x++) {
            for (int y = 0; y < 3; y++) {
                scaledUp[x][y] = vertexes[x][y] * multiplier;
            }
        }
        return new Triangle(scaledUp);
    }
}

Design a Vertex class (signatures only, no implementation needed) that could simplify this — a triangle is really a collection of three vertices, each with an x and a y coordinate.

Only the signatures are designed, in shorthand: name, parameter types without parameter names, and a trailing comment.

class Vertex {
    Vertex(); // Construct a new vertex at (0, 0)
    Vertex(double, double);
    double distance(Vertex); // distance to another vertex
    Vertex scale(double); // multiply the coordinates by the given amount
}

Triangle is then rewritten on top of it. Either a Vertex[] or three Vertex member variables would do; the version below takes the second option, even though the question phrases the constructor as Triangle(Vertex[]):

public class Triangle {
    private Vertex a;
    private Vertex b;
    private Vertex c;

    public Triangle(double a, double b, double c) {
        double dividend = (square(a) - square(b) - square(c));
        double cx = dividend / (-2 * c);
        double cy = Math.sqrt(square(b) - square(cx));

        this.a = new Vertex();
        this.b = new Vertex(c, 0);
        this.c = new Vertex(cx, cy);
    }

    public Triangle(Vertex a, Vertex b, Vertex c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public Triangle(double[][] vertexes) {
        this.a = new Vertex(vertexes[0][0], vertexes[1][0]);
        this.b = new Vertex(vertexes[0][1], vertexes[1][1]);
        this.c = new Vertex(vertexes[0][2], vertexes[1][2]);
    }

    public double perimeter() {
        return a.distance(b) + b.distance(c) + c.distance(a);
    }

    public Triangle scale(double multiplier) {
        return new Triangle(a.scale(multiplier), b.scale(multiplier),
                c.scale(multiplier));
    }
}

perimeter() collapses from six local variables and three four-argument calls to one line, and scale from a nested loop over anonymous indices to one call per vertex. Introducing Vertex moves the x/y bookkeeping into a single-responsibility class, so Triangle’s own methods read as “distance between vertices” and “scale each vertex” rather than juggling raw array indices — the cohesion argument taken up properly in java-cohesion-and-coupling.

Two things about the original listing:

  • The three-argument constructor is the law of cosines. With \(\mathcal{A}\) at the origin and \(\mathcal{B}\) at \((c, 0)\), cx \(= (b^2 + c^2 - a^2) / 2c = b\cos\alpha\) and cy \(=\sqrt{b^2 - cx^2}\), i.e. \(\mathcal{C}\)’s coordinates. \(\mathcal{A}\) is at \((0,0)\), and the code writes new double[]{0, c, cx} for the x row, so \(\mathcal{B}\) has y-coordinate 0 and x-coordinate c.
  • perimeter() does not actually compute the perimeter. distance is declared (double x1, double x2, double y1, double y2) — both x’s, then both y’s — but every call passes coordinates point-wise: distance(x0, y0, x1, y1) binds x2 to y0 and y1 to x1, so the result is \(\sqrt{(x_0 - y_0)^2 + (x_1 - y_1)^2}\). That is a live bug, and it is caused by exactly the thing the exercise is arguing against: an argument list of four bare doubles carries no information about which number is an x and which is a y. The Vertex rewrite makes the same mistake impossible to write, because a.distance(b) has nowhere to put a coordinate in the wrong slot.

Question 3 — Recursive call stack (bonus)

class Reverser {
    static void reverse(int[] arr) {
        int n = arr.length;

        if (n == 1) {
            return;
        }

        // copy [1..n - 1] into rest
        int[] rest = new int[n - 1];
        for (int i = 1; i < n; i++) {
            rest[i - 1] = arr[i];
        }

        arr[n - 1] = arr[0];

        reverse(rest);
    }

    public static void main(String[] args) {
        int[] numbers = {42, 24, 11};
        reverse(numbers);
    }
}

Sketch the state of the call stack and heap just prior to the third call to reverse.

“Just prior to the third call” means two reverse frames are already live and neither has returned, so all three frames are drawn solid:

Figure 21: Task 4’s answer: the stack and heap immediately before the third call to reverse. Three live frames, four heap arrays. Each call’s rest becomes the next call’s arr - which is why the second and third boxes each have two arrows into them - while main’s numbers and the first call’s arr are two names for one array that has already been written to.

Reading the trace off the figure:

call arr on entry rest built arr[n-1] = arr[0] leaves arr as
1st {42, 24, 11} {24, 11} {42, 24, 42}
2nd {24, 11} {11} {24, 24}
3rd {11} — (n == 1, returns) {11}

Two structural points the picture makes:

  • rest is a fresh array each time. main’s numbers and the first call’s arr are the same box (one arrow each into {42, 24, 42}), but every deeper call works on a copy. Only the top frame’s write ever reaches numbers.
  • Reverser.reverse does not reverse anything. After main returns, numbers is {42, 24, 42} — the 42 has been copied over the 11 and nothing has moved. Each call writes its own first element into its own last slot and then hands a copy to the next call, so every write below the first frame lands in an array nobody keeps a reference to. The call stack sketch is what makes that visible; reading the source alone, the recursion looks plausible.

The base case is n == 1, so an empty array never terminates it — reverse(new int[0]) reaches new int[n - 1] with n == 0 and throws NegativeArraySizeException. A base case of n <= 1 would be the safer guard, the same widening move the week 5 practical makes for RecursiveFibonacci — see week5-lab-debugging.

Week 4

Exceptions

See csse2002 for course logistics. A supplementary lecture on java-version-control also ran this week.

Code samples are in the course CodeCamp playlist and Git repo.

Outline

  1. Exceptions: what an exception is, the hierarchy, checked vs unchecked, try/catch, throw, throws, finally, custom exceptions.
  2. Specification: Javadoc → Restrictiveness → Generality → Formality → Contracts → Defensive Programming.

Exceptions

See java-exceptions — the exception hierarchy, checked vs unchecked exceptions, try/catch/throw/throws/finally, and custom exceptions. The finally exercise (Good Morning / hello / world) is worked there; week5-tutorial-exceptions then pushes the same tracing into nested blocks.

Specification

This repeats Week 3’s material: Javadoc, restrictiveness, generality, clarity, formality, contracts, defensive programming. See java-specification, which also has an early-return variant of the search generality example and an Effective Java citation for defensive programming/doc comments.

The rest of this section covers the examples that are not in that note.

The search array — why “an index” isn’t a specification

Restrictiveness on search, in three steps. The first spec:

/**
 * Returns an index (i) of ar such that ar[i] == x, if any.
 */
public int search(int[] ar, int x) { … }

This is a bad specification. It is silent about x not being in ar, and by its silence it allows any value to be returned. A return of 1 or 0 could equally mean “it’s at index 1/0” or “I didn’t find it”.

Adding else, return -1 is better but still bad. This array is why:

Figure 22: The array ar is the counterexample to the improved spec: 3 sits at both index 1 and index 4, so a specification asking only for an index i with ar[i] == x lets an implementation return either, and lets it return a different one on each call.

Nothing in that spec requires that you get the lowest index, or that you get the same answer running multiple times. Only “return the smallest index (i) of ar such that ar[i] == x, if any, else return -1” fixes both. Two different implementations can both satisfy that wording, which is the generality example.

Worked: is this a good specification?

Four specs, each judged against the three criteria: restrictive, general, clear.

/**
 * Sorts the given array.
 */
public void sort(int[] ar) { … }

Not restrictive enough: ascending or descending is never stated, so both satisfy it.

/**
 * Calculate x to the power of two with Math.pow.
 */
public int square(int x) { … }

Not general enough — the classic generality failure. It names an implementation (Math.pow), so it describes how rather than what, and an x * x implementation that computes exactly the same answer technically violates it.

/**
 * Returns the list of ResourceContainers stored by this instance.
 */
public List<ResourceContainer> getResources() { … }

Not restrictive enough about aliasing: it doesn’t say whether the caller gets the internal list or a copy, so it doesn’t say whether adding to the returned list changes the object — see java-mutability.

/**
 * Calculate the nth value of the fibonacci sequence.
 */
public long fib(int n) { … }

Not clear enough: it doesn’t fix the indexing (is fib(0) 0 or 1?), and says nothing about negative n or about n large enough to overflow long.

Contracts — the caller’s obligation, and \result

The contract form of withdraw carries a postcondition on the return value as well as on the state. The call site follows it:

/**
 * Withdraws an amount from this account.
 *
 * @require amount >= 0
 * @require amount <= getBalance()
 * @ensure getBalance == \old(getBalance()) - amount
 * @ensure \result == getBalance()
 */
public int withdraw(int amount) {
    // no need to check the conditions
}
int balance = myAccount.withdraw(amt);

The method body needs no checks at all, because it is up to the calling code to make sure it fulfils its side of the contract, i.e. 0 <= amt <= myAccount.getBalance(). Written without a contract, the same method checks both conditions itself and returns the sentinel -1 on failure, which pushes an if (balance == -1) { … } into every call site.

The tags are spelt @require/@ensure here and @requires/@ensures elsewhere. Both spellings are used across the course. In the first @ensure line the left-hand getBalance is the call getBalance().

findMax — the undefended version, then the defended one

Defensive programming, before and after. The undefended version is code only, with no Javadoc:

public int findMax(int[] numbers) {
    int max = Integer.MIN_VALUE;
    for (int i = 0; i < numbers.length-1; i++) {
        if (numbers[i] > max) {
            max = numbers[i];
        }
    }
    return max;
}

The defended version adds the full specification (@param, @return, @throws IllegalArgumentException if the array is null or empty, @requires numbers != null && numbers.length > 0, @ensures the maximum is returned) and the guard clause that throws it. That version is in java-specification.

The loop bound also changes between the two versions, from i < numbers.length-1 to i < numbers.length. The undefended version never examines the last element.

Key takeaways

  • A specification describes the contract between a method and its client.
  • It explains what the method does, not how it is implemented.
  • A good specification clearly states its preconditions (true before the call), postconditions (true after it finishes successfully), and side effects (any other changes it makes to the system).
  • Clear specifications make code easier to understand, use, and maintain.

Further reading: Oracle’s Preconditions, Postconditions, and Class Invariants and Assertions guides, plus Effective Java (3rd Edition) Item 56, “Write doc comments for all exposed API elements”.

Method Dispatch and Casting

Applied class exercises for week 4, covering java-polymorphism (dynamic method dispatch) and java-casting in more depth.

On the HTML site, fill in each blank with your answer (as a quoted string, e.g. "Car.topSpeed()"), 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).

The five rules of method dispatch

Method dispatch follows five rules. Everything else in the class is an application of them:

  1. The compiler deduces an apparent type (also called a compile-time type) for each object, using type information from variable and method declarations.
  2. Each object also has an actual type (also called a runtime type), obtained when it is created by new: the type of the class that constructs it.
  3. The compiler ensures the apparent type it deduces is always the actual type, or a superclass of the actual type.
  4. The compiler determines what calls are legal based on the object’s apparent type.
  5. Dispatching causes method calls to go to the object’s actual code — that is, the code provided by its actual type.

Figure 23: The two types every reference carries, and what each one decides, on the declaration C variable = new R();, where C is a superclass of R or is R. The apparent type C decides whether variable.method() is legal; the actual type R decides which code it runs.

Rules 4 and 5 are the whole exercise: legality is decided from the apparent type, the code that runs comes from the actual type. The two are settled at different times and can disagree.

Question 1 — Apparent type vs actual type

class Animal {
    void eat() {...}
}
class Lion extends Animal {}
class Dog extends Animal implements Pet {
    void eat() {...}
    void eat(int howMuch) {...}
}
class Poodle extends Dog {}
interface Pet {}

A diagram makes it easier to see how the classes are related and which method will be invoked:

Figure 24: The Question 1 hierarchy. Superclass above; a solid rectangle for a class and a dashed rectangle for an interface; the class name in bold serif over a rule, members below as + name(); a solid line for extends and a dashed line for implements, both with the same filled arrowhead. The SOLID diagrams draw implements with an open arrowhead instead.

What happens when you call simba.eat(200), given Lion simba = new Lion();?

simba’s apparent AND actual type is Lion, which has no eat(int) method (only the no-arg eat() inherited from Animal) — the compiler rejects the call outright, since legality is checked against the apparent type’s available methods (rule 4).

The full table, one line at a time:

Statement Outcome
Dog evie = new Dog(); OK
Animal animal = evie; OK (upcast, implicit)
Lion mufasa = animal; Must be cast. Will fail (an Animal referencing a Dog is never a Lion).
Dog harlee = animal; Must be cast. Will succeed — the cast is written out as if (animal instanceof Dog harlee) ...
Poodle bruiser = evie; Must be cast. Will fail (evie’s actual type is Dog, not Poodle).
Lion simba = new Lion(); OK
Lion scar = new Poodle(); Will not compile — Poodle and Lion share no inheritance relationship.
Pet charley = new Poodle(); OK (Poodle extends Dog, which implements Pet).
Dog lassie = charley; Must be cast. Will succeed.
Animal scooby = charley; Will not compile — Pet is not related to Animal (an interface doesn’t know about unrelated classes).
simba.eat(); OK
simba.eat(200); No method found — compile error.

Task 0 — Draw the hierarchy

Draw a diagram which makes the code below easier to understand.

In the following, all classes, interfaces, and members are public, and many details have been omitted:

class Location {...}

interface RoadLegal {
    int topSpeed();
    boolean licenceRequired();
}

interface PublicTransport {
    double calculateFare(Location start, Location end);
}

class Vehicle {
    int travelTime(Location start, Location end) {...}
    int topSpeed() {...}
}

class HumanPowered extends Vehicle {
    int getWeight() {...}
    int topSpeed() {...}
}

class Motorised extends Vehicle implements RoadLegal {
    int travelTime(Location start, Location end) {...}
    int topSpeed() {...}
    boolean licenceRequired() {...}
}

class Skateboard extends HumanPowered {}

class Bicycle extends HumanPowered implements RoadLegal {
    boolean licenceRequired() {...}
}

class Motorbike extends Motorised {
    int topSpeed() {...}
    int travelTime(Location location) {...}   // overload, not an override
}

class Car extends Motorised {
    int topSpeed() {...}
}

class Taxi extends Car {}

class Bus extends Motorised implements PublicTransport {
    int topSpeed() {...}
    double calculateFare(Location start, Location end) {...}
}

Figure 25: Task 0’s answer. Same conventions as Figure 24: dashed rectangles are interfaces, solid lines are extends, dashed lines are implements, both with a filled arrowhead, superclass above. Only the methods each type actually declares are listed — that is what makes the dispatch questions answerable by eye. Location is drawn floating and unconnected. Motorbike declares travelTime(Location) — one argument — which is an overload of, not an override of, Vehicle.travelTime(Location, Location).

Two things to read off the picture before attempting anything else:

  • RoadLegal is reached twice by different routes — once through Motorised, once directly from Bicycle. So Motorbike, Car, Taxi, Bus and Bicycle are all RoadLegal, but Skateboard is not.
  • Bicycle implements RoadLegal yet declares only licenceRequired(). It satisfies topSpeed() with the one it inherits from HumanPowered.

Task 1 — Does it compile?

For the creation and usage of objects below, indicate whether the statements would compile or not. If it would not compile, explain why.

# Statement(s) Verdict
1 Vehicle bus = new Bus(); Compiles, no error. Bus is implicitly upcast to Vehicle.
2 Motorised skateboard = new Skateboard(); Does not compile. There is no relationship between Motorised and Skateboard, so a Skateboard can never be an instance of Motorised.
3 Motorbike vehicle = new Vehicle(); Does not compile. Going from Vehicle to Motorbike is a downcast, so an explicit cast is required.
4 Motorised motorbike = new Motorbike();
Location destination = new Location();
motorbike.travelTime(destination);
Does not compile. Motorised and its parent classes have no method matching the signature travelTime(Location). The one-argument overload exists only on Motorbike, and legality is judged from the apparent type.
5 Motorbike motorbike = new Motorbike();
Location start = new Location();
Location end = new Location();
motorbike.travelTime(start, end);
Compiles, no error. travelTime() is overloaded in Motorbike, so both the one- and two-Location versions are available through a Motorbike-typed variable.

Bonus:

# Statement(s) Verdict
1 Car car = new Taxi();
Taxi taxi = car;
Does not compile. Going from Car to Taxi is a downcast, so an explicit cast is required.
2 Vehicle bike = new Bicycle();
bike.getWeight();
Does not compile. Vehicle has no method matching the signature getWeight() — it is declared on HumanPowered.
3 Motorised bus = new Bus();
PublicTransport trip = bus;
trip.calculateFare(start, end);
Does not compile. Motorised cannot be implicitly cast into PublicTransport.

Items 4 and 5 are the pair worth memorising. A Motorbike object really does have a one-argument travelTime — item 5 shows both overloads are reachable through a Motorbike-typed variable. Widen the variable to Motorised and the very same object stops accepting the call (item 4), because legality is judged from the apparent type and nothing above Motorbike declares that signature.

Task 2 — Which implementation is called?

For each, what method implementation is actually called? (Assume location1 and location2 are Location objects.)

Vehicle vehicle = new Taxi(); vehicle.topSpeed(); →

Vehicle vehicle = new Bicycle(); vehicle.topSpeed(); →

RoadLegal roadLegal = new Bicycle(); roadLegal.topSpeed(); →

Vehicle vehicle = new Motorbike(); vehicle.travelTime(location1, location2); →

Call Dispatches to
Vehicle vehicle = new Taxi(); vehicle.topSpeed(); Car.topSpeed()
Vehicle vehicle = new Bicycle(); vehicle.topSpeed(); HumanPowered.topSpeed()
RoadLegal roadLegal = new Bicycle(); roadLegal.topSpeed(); HumanPowered.topSpeed()
Vehicle vehicle = new Motorbike(); vehicle.travelTime(location1, location2); Motorised.travelTime(Location, Location)

Read each one off Figure 25: start at the actual type and walk up until you find a box that lists the method.

  • Taxi declares nothing, so topSpeed() comes from Car.
  • Bicycle declares only licenceRequired(), so topSpeed() comes from HumanPowered — and this is unchanged when the apparent type is the RoadLegal interface. Dispatch never consults the apparent type (rule 5).
  • Motorbike overrides topSpeed() and overloads travelTime with a one-argument version, but never overrides the two-argument one, so that call lands on Motorised.

Casting — the three rules

In Java, when changing the apparent type of a value:

  1. If the new apparent type is a superclass of the old apparent type, the cast can be implicit.
  2. If the new apparent type is a subclass of the old apparent type, the cast should be performed via an instanceof check.
  3. If the new apparent type and old apparent type have no inheritance relationship, Java will refuse to compile.

Task 3 — instanceof: compiles? implicit?

Assume that xyz is an instance of class Xyz — e.g. bus is an instance of Bus. For each cast, indicate whether (1) it would compile and (2) it could be implicit.

Expression Compiles Implicit Why
if (bus instanceof Vehicle vehicle) ✓ ✓ Vehicle is a superclass of Bus — rule 1.
if (car instanceof Taxi taxi) ✓ ✗ Taxi is a subclass of Car, so it needs the runtime check — rule 2.
if (motorised instanceof Bicycle bike) ✗ — Motorised and Bicycle are siblings under Vehicle with no relationship — rule 3.
if (motorbike instanceof RoadLegal legal) ✓ ✓ Motorbike extends Motorised, which implements RoadLegal.
if (taxi instanceof Vehicle vehicle) ✓ ✓ Vehicle is a superclass all the way up the Taxi → Car → Motorised → Vehicle chain.

The “Implicit” cell is left blank for the row that does not compile, rather than marked ✗ — there is nothing to decide once the code is rejected.

Task 4 — Where would an electric scooter fit?

If we wanted a class to represent an electric scooter, where would that fit in the hierarchy?

The answer is deliberately open; this is a discussion question. Not all models fit all circumstances, and single inheritance makes this one difficult.

An electric scooter is motorised and human-scale, road-legal in some jurisdictions and not others — and Java gives you exactly one superclass. The escape hatch the rest of the course teaches is to push the shared behaviour into interfaces rather than a class (see java-solid-principles on interface segregation, and week11-tutorial-dependency-inversion).

Where this reappears

The same two-phase rule — overload chosen at compile time from the static types, override resolved at run time from the actual type — comes back in revision Questions 19–21, worked with the BruceWayne/Batman/kapow example. See 2026-05-28-course-summary-and-exam-preparation and 2026-03-12-object-oriented-programming-ii.

Week 5

Testing

See csse2002 for course logistics.

Outline

  1. Levels of Testing
  2. Test Frameworks
  3. Black Box Testing
  4. White Box Testing
  5. Test Driven Development (TDD)

Testing

See java-testing — the four levels of testing (unit → integration → system → acceptance), regression testing, black-box vs white/glass-box testing (smoke tests, boundary tests, equivalence classes, code coverage), and TDD.

JUnit

See java-junit — @Test, @Before/@After, Assert methods, and testing for expected exceptions.

Black box: the bus example

The black-box example is a bus. The specification is all you get: getCurrentPassengers() and getAverageCount() are given as Javadoc only, with their bodies elided ({...}). With a maximum capacity of 80, the equivalence classes and their boundary probes are:

Class Values Boundary tests
Valid – Empty 0 -1, 0, 1
Valid – Normal 1 – 79 Covered by above and below
Valid – Full capacity 80 79, 80, 81
Invalid – -1, 81

This gives the minimal boundary set -1, 0, 1, 79, 80, 81.

Summary: the black-box method

The black-box method in six points:

  1. Black box testing: no knowledge of implementation, only specification.
  2. JUnit is a test framework.
  3. Tests must not violate preconditions.
  4. Start with smoke tests.
  5. Expand test suite with boundary tests.
  6. Stop when confidence is high.

Worked: coverage of register

One short method, with the same question asked at each of the three levels of white-box coverage:

public void register(int x) {
    if (x > 0) {
        positives += 1;
    }
    if (x % 2 == 0) {
        evens += 1;
    }
}

What input for x would give statement coverage? Any odd positive value, e.g. x = 1, gives only a partial run: if (x > 0), positives += 1 and the if (x % 2 == 0) test are all executed, but evens += 1 is missed. x = 2 alone executes every statement.

What input for x would give branch coverage? Branch coverage means each branch is tested for the true case and the false case. x = 2 makes both conditions true, which is half of it. Adding x = -1 makes both conditions false as well. So x = 2 and x = -1: two tests.

What input for x would give path coverage? Path coverage means every path through the code is traversed. Drawn as a decision tree, the code has four exit leaves, so there are four paths, each with its own input:

Path x
x > 0 && x % 2 == 0 2
x > 0 && !(x % 2 == 0) 1
!(x > 0) && x % 2 == 0 -2
!(x > 0) && !(x % 2 == 0) -1

The tree, with the four inputs placed on the paths they drive, is under “White box technique: code coverage” in java-testing, along with the loop argument that follows it: a 100-iteration loop containing one if has \(2^{100}\) paths, so exhaustive path coverage is abandoned in favour of the 0/1/2-iteration approximation.

The worked JUnit white-box example, DiscountCalculator, is in java-junit: five reachable returns, five tests.

Exercise (HW): black box tests for contains

/**
 * Determine if value is contained within the array.
 *
 * @requires array is sorted in ascending order.
 * @return true if value is in the array, false otherwise.
 */
boolean contains(int[] array, int value) {

}

Write black box tests for contains — from this specification only, without seeing the body.

TipSketch of an answer

Worked the same way as the bus example:

  • @requires array is sorted in ascending order is a precondition, so summary point 3 applies: an unsorted array is not a legal test case. Passing one proves nothing, whatever contains returns.
  • Equivalence classes on the array: empty; one element; many elements. On the value: present in the array; absent.
  • Boundary probes (from the collection and whole-number rows of the boundary table in java-testing): empty array; single-element array with the value present and with it absent; value equal to the first element; value equal to the last element; value falling strictly between two neighbours; value below the minimum and above the maximum; Integer.MIN_VALUE / Integer.MAX_VALUE.
  • array == null is a reference-type boundary, but the spec neither permits nor forbids it, so whether it is a legal test case depends on reading @requires as implying non-null.

Further material

I hear and I forget. I read and I remember. I do and I understand.

— Confucius (according to popular belief)

The CodeCamp playlist has supplementary material and the Git repo has the code samples. Muddy cards as usual.

Debugging

Practical for week 5: using the IntelliJ debugger to find and fix bugs in a small provided codebase of chat bots (ChatBot implementations) — reinforcing java-junit (the provided tests are what reveal each bug) and java-exceptions (RecursiveFibonacci’s bug manifests as a StackOverflowError).

This practical is hands-on IntelliJ-debugger work rather than a computable Q&A, so there are no interactive checks here — just each bug and its fix, as a static reference/answer key.

Setup and ground rules

A provided .zip (from Blackboard) contains thirteen files — ChatBot.java (the shared interface), five bot implementations, and a JUnit test class for each:

CachedFibonacci.java              MockBot.java
CachedFibonacciTest.java          MockBotTest.java
ChatBot.java                      MultiplayerGuessingGameBot.java
CommitBot.java                    MultiplayerGuessingGameBotTest.java
CommitBotTest.java                RecursiveFibonacci.java
GuessingGameBot.java              RecursiveFibonacciTest.java
GuessingGameBotTest.java

The setup is itself part of the exercise: create an IntelliJ project with a src/ source root (blue) and a test/ test source root (green), read the top of the files to discover they all declare a debugging package, create debugging/ under both roots, and copy the files in accordingly. If it worked, the run shows 37 tests, 24 of them failing.

This is also a Git exercise (java-version-control): initialise a repository before you start and commit after each bug fix with a message describing the fix, so the history is one commit per defect.

ImportantGround rules

The practical is about learning the debugger, so for this practical only, modifying the code to add debugging print statements is banned. Modifying the code at all is banned until you have found the bug and are ready to start fixing it. The ban applies to the tests as well.

For the number-guessing bot the work splits into three separate tasks, and they are the actual method being taught — the fix is the last step, not the first:

  1. Where does the code stop working?
  2. Why does the code stop working?
  3. How can you fix the code so that it does work?

Every other bot gets the same sequence in compressed form: step through the failing tests with the debugger to work out why they fail, then implement the fix, then repeat until the tests pass.

Every bot implements one interface, so a failing test always points at one replyTo call:

public interface ChatBot {
    String replyTo(String username, String message);
}

The method takes the user’s username and their message, and either replies or returns null to indicate no response.

Bug 1 — MockBot

MockBot responds to all messages with a copy of the message in alternating caps:

[you]> its a mock bot world after all iTS a mock boT WoRld afTeR all
ChatBot bot = new MockBot();
System.out.println(bot.replyTo("you", "its a mock bot world after all"));
// iTS a mock boT WoRld afTeR all

The rule is not “alternate letter by letter” but a threshold on the letter: once the message has been folded to uppercase — which is exactly what the fix adds — a letter at or below 'O' comes out lowercase and a letter above 'O' comes out uppercase. (Check it against the example: a, b, c, d, e, f, i, k, l, m, o all sit at or below O in the alphabet and are printed lowercase, while r, s, t, w sit above it and are printed R, S, T, W. The listing below is the buggy body, i.e. before that fold — run as it stands it compares the raw lowercase codes instead, which is the bug.)

private String mock(String message) {
    StringBuilder result = new StringBuilder();
    for (char letter : message.toCharArray()) {
        if (letter > 'O') {
            result.append(Character.toUpperCase(letter));
        } else {
            result.append(Character.toLowerCase(letter));
        }
    }
    return result.toString();
}

The bug comes from improper handling of lowercase letters: all lowercase letters are converted to capitals. Converting the message to uppercase first fixes it.

Figure 26: Why every lowercase letter comes out shouted, and what toUpperCase fixes. Comparing a char with > compares its numeric code, and the entire lowercase alphabet (97-122) sits above the threshold letter O (79), so the buggy loop routes all of a-z into the toUpperCase branch. Folding the message to uppercase first collapses a-z onto A-Z, putting each letter back on the side of the threshold its position in the alphabet intends.

Comparing two chars with > compares their numeric codes, and Java’s letter codes run 'A'–'Z' = 65–90 then 'a'–'z' = 97–122. Every lowercase letter therefore exceeds 'O' (79) regardless of where it sits in the alphabet, so the buggy loop sends the whole of a–z down the toUpperCase branch: every lowercase letter is converted to a capital.

Normalising the message to uppercase before the loop puts every letter into the 65–90 range, where the comparison against 'O' means what it was meant to mean:

private String mock(String message) {
    ...
-   for (char letter : message.toCharArray()) {
+   for (char letter : message.toUpperCase().toCharArray()) {
    ...
}

The debugger route to this: set a breakpoint inside the loop, watch letter and the branch taken, and the first lowercase character shows the wrong branch being entered.

Bug 2 & 3 — GuessingGameBot

A bot that plays a number-guessing game: the user asks whether the secret “magic number” is higher or lower than a guess, and the bot answers.

[you]> help
Guessing game bot!
There are 3 options
1) guess higher <number>
2) guess lower <number>
3) guess equal <number>
[you]> guess higher 2
yes
[you]> guess lower 5
no
[you]> guess equal 3
you lose!

Two independent bugs.

Bug 2 — message splitting. split(String) breaks a message into words on spaces:

private static List<String> split(String input) {
    ...
    while (index != -1) {
        newIndex = input.indexOf(' ', index + 1);
        if (newIndex == -1) {
            output.add(input.substring(index));
        } else {
            output.add(input.substring(index, newIndex));
        }
        index = newIndex;
    }
}

Bug 3 — comparison logic. The higher/lower branches compare the wrong way:

public static String replyTo(String message) {
    ...
    if (type.equals("higher")) {
        ...
        return guess > SECRET_NUMBER ? "yes" : "no";
    } else if (type.equals("lower")) {
        ...
        return guess < SECRET_NUMBER ? "yes" : "no";
        ...
    } else if (type.equals("equal")) {
    ...
}

Reading the documentation in the source files helps in working out how the code functions. Both bugs are only visible once you know what split and replyTo are each supposed to return.

Bug 2 fix. Messages are not split correctly, leaving extra whitespace before words, because substring() includes the char at the first index it is given.

Figure 27: Bug 2 traced on the message the transcript uses. Top: the substring ranges the buggy loop produces, because index is reassigned to the position OF the space rather than one past it, so every word after the first keeps a leading space. Bottom: the ranges after the fix. The leading space is not cosmetic - it makes type.equals(higher) false and would make Integer.parseInt on the last token throw.

Stepping "guess higher 2" through the buggy loop gives ["guess", " higher", " 2"] — the two later tokens carry a leading space, which is enough to make type.equals("higher") false and to make Integer.parseInt(" 2") throw a NumberFormatException. The fix advances past the space:

private static List<String> split(String input) {
    while (index != -1) {
        newIndex = input.indexOf(' ', index + 1);
        if (newIndex == -1) {
            output.add(input.substring(index));
+           break;
        } else {
            output.add(input.substring(index, newIndex));
        }
-       index = newIndex;
+       index = newIndex + 1;
    }
}

The break is not optional, and it is a consequence of the other line: with index = newIndex + 1, the loop’s own while (index != -1) guard can no longer stop it — on the last word newIndex is -1, so index becomes 0 and the loop restarts from the beginning of the string forever. Adding the + 1 without the break trades a wrong answer for an infinite loop.

Bug 3 fix. Guesses are checked against the secret number incorrectly. Swapping the > and < fixes it.

public static String replyTo(String message) {
    ...
    if (type.equals("higher")) {
        ...
-       return guess > SECRET_NUMBER ? "yes" : "no";
+       return guess < SECRET_NUMBER ? "yes" : "no";
    } else if (type.equals("lower")) {
        ...
-       return guess < SECRET_NUMBER ? "yes" : "no";
+       return guess > SECRET_NUMBER ? "yes" : "no";
        ...
    } else if (type.equals("equal")) {
    ...
}

The reading that makes the swap obvious: guess higher 2 asks “is the secret higher than 2?”, so the answer is "yes" exactly when 2 < SECRET_NUMBER. Checked against the transcript above — guess higher 2 → yes and guess lower 5 → no — the fixed code says the secret is greater than 2 and not less than 5, which the guess equal 3 → you lose! line is consistent with.

Bug 4 & 5 — MultiplayerGuessingGameBot

The multiplayer variant lets several users each submit one guess; whoever is closest wins, and only the host may finish the game:

[you]> start game
Starting new game...
[you]> guess 12
[root]> guess 5
[admin]> guess 100
[test]> guess 34
[root]> finish game
You do not have a game running.
Host must finish game.
[you]> finish game
The secret number was 13
1) you (12)
2) root (5)
3) test (34)
4) admin (100)

Two independent bugs.

Bug 4 — host check inverted:

public String replyTo(String username, String message) {
    ...
    if (username.equals(host)) {
        return "You do not have a game running.\n"
                + "Host must finish game.";
    }
    ...
}

Bug 5 — leaderboard rank off-by-one:

private String results() {
    ...
    int rank = 0;
    ...
}

Bug 4 fix. Finishing a game is not handled correctly. The user finishing the game should be the same as the host; the current implementation does the opposite. The refusal message belongs to the non-host:

public String replyTo(String username, String message) {
    ...
-   if (username.equals(host)) {
+   if (!username.equals(host)) {
    ...
}

Read against the transcript: [root]> finish game is refused because root is not the host, and [you]> finish game succeeds because you started the game. The buggy version does exactly the reverse — the host is the only user who cannot end their own game.

Bug 5 fix. The leaderboard has an off-by-one error in the ranking: it starts from zero instead of one.

private String results() {
    ...
-   int rank = 0;
+   int rank = 1;
    ...
}

The transcript’s leaderboard begins at 1) you (12), so the counter that labels the rows is a display index rather than an array index — and Java’s habit of counting positions from zero is what makes int rank = 0; look right at a glance.

Bug 6 & 7 — CommitBot

Lets a user generate a random commit message (commit new), save the last-generated one (commit save), and reload it later (commit load):

[you]> commit new
I know what I am doing. Trust me.
[you]> commit save
Commit saved
[you]> commit new
Does this work
[you]> commit load
I know what I am doing. Trust me.

Two independent bugs. The transcript requires that commit load returns the message that was saved, not the one most recently generated.

Bug 6 — generated message never recorded as “last”:

public String replyTo(String username, String message) {
    ...
            String commit = generateMessage();
            return commit;
    ...
}

Bug 7 — load reads from the wrong map:

public String replyTo(String username, String message) {
    ...
        if (message.endsWith("load")) {
            if (!lastMessages.containsKey(username)) {
                return "No saved message to load";
            }
            return lastMessages.get(username);
        }
    ...
}

Bug 6 fix. The last generated commit message is not recorded when it is generated. commit save reads whatever lastMessages holds for the user, so if commit new never writes there, save has nothing (or something stale) to promote:

public String replyTo(String username, String message) {
    ...
            String commit = generateMessage();
+           lastMessages.put(username, commit);
            return commit;
    ...
}

Bug 7 fix. The load command loads commit messages from the last message rather than the saved message.

public String replyTo(String username, String message) {
    ...
        if (message.endsWith("load")) {
-           if (!lastMessages.containsKey(username)) {
+           if (!savedMessages.containsKey(username)) {
                return "No saved message to load";
            }
-           return lastMessages.get(username);
+           return savedMessages.get(username);
        }
    ...
}

The two maps exist for two different lifetimes — lastMessages is whatever was generated most recently, savedMessages is what the user chose to keep — and each bug is one of them being used where the other belongs. The bugs mask each other, so the transcript is worth re-reading between fixes. Fix bug 6 alone and commit load starts returning the most recently generated message — "Does this work" — rather than the saved one; fix bug 7 alone and savedMessages still has nothing in it to load. Only both fixes together reproduce the transcript’s last line.

Bug 8 — RecursiveFibonacci (bonus)

The tests throw a “StackOverflow” exception. A stack overflow exception is thrown when a function recursively calls itself so many times that the program runs out of stack memory. A recursive method needs a base case so that the function knows when to stop. Two things to check: whether this code has a base case, and whether it is being reached.

The issue arises when x > 1: the recursive calls to calculate then include subtractions of 2 or greater, so the base case of x == 1 is skipped, resulting in infinite calls of negative numbers. The base case is written n == 1, an equality test, so any step that moves n past 1 by more than one at a time misses it entirely and the recursion runs away into the negatives.

Two fixes, given \(\mathcal{F}(1) = \mathcal{F}(2) = 1\):

// Preferred: widen the existing base case so it cannot be stepped over.
public static int calculate(int n, int x) {
-   if (n == 1) {
+   if (n <= 2) {
        return 1;
    }
}
// Alternative: add an explicit zero case.
public static int calculate(int n, int x) {
+   if (n == 0) { // or n < 1
+       return 0;
+   }
    ...
}

The first is preferred. The second preserves and tolerates recursive calls that violate the precondition, n >= 1; the first removes the offending calls where n < 1. In the language of java-specification: the second fix makes the method cope with arguments outside its own precondition, which quietly widens the contract; the first fix makes those calls never happen.

The general lesson is about the shape of a guard rather than this method: a base case tested with == is only safe if the recursion is guaranteed to land exactly on it. Testing with <= is robust to any step size.

A naming point: StackOverflowError is an Error, not an Exception — both are Throwables, but Error marks conditions a program is not expected to catch and recover from. The distinction is drawn in java-exceptions; calling it an exception is informal.

Bug 9 — CachedFibonacci (challenge)

“Code is broken. Please fix. Good luck.” The symptom is that the results are wrong for larger Fibonacci numbers only — small inputs pass.

The cache is two parallel arrays, cacheKeys and cacheValues, kept in most-recently-used order: on a hit at position index, the entry is shuffled to the front.

...
int key = cacheKeys[index], value = cacheValues[index];
for (int i = index - 1; i >= 0; --i) {
    cacheKeys[i + 1] = cacheKeys[i];
    cacheValues[i + 1] = cacheValues[i];
}
cacheKeys[0] = key;
cacheValues[0] = value;
...

The code gives incorrect results for larger Fibonacci numbers. The problem is that the index of the current number n is not updated after its position is shuffled to the front of the cache.

Figure 28: The move-to-front shuffle and the variable it forgets. The slot values a..f stand in for cache contents. Slots 0 through index-1 each shift one place right and the promoted key k is written into slot 0, so after the shuffle every entry at or below index has moved. index itself is untouched, so it now names a different entry than the one just looked up - which is why only lookups that hit deep in the cache, i.e. larger inputs, come back wrong.

...
int key = cacheKeys[index], value = cacheValues[index];
for (int i = index - 1; i >= 0; --i) {
    cacheKeys[i + 1] = cacheKeys[i];
    cacheValues[i + 1] = cacheValues[i];
}
cacheKeys[0] = key;
cacheValues[0] = value;
+ index = 0;
...

This bug is a good argument for the ground rule about the debugger. The symptom (“wrong only for larger numbers”) is the giveaway once the mechanism is on paper: index == 0 is a hit at the front, where the shuffle moves nothing and the stale value is accidentally correct. Only a hit at index > 0 — which needs a cache deep enough to have been populated, i.e. a larger input — leaves index naming the wrong slot. Reading the code alone, the missing line is invisible because nothing is written incorrectly; a variable is simply left behind by a state change happening around it.

Exceptions

Applied class exercises for week 5, tracing execution through nested try/catch/finally blocks — reinforcing java-exceptions and 2026-03-19-exceptions. Two exception families are defined up front and used throughout. It helps to draw a diagram of the inheritance relationships between the classes, because every answer below turns on which class is a subclass of which.

class E1 extends Exception {};      class F1 extends Exception {};
class E2 extends E1 {};             class F2 extends F1 {};
class E3 extends E1 {};             class F3 extends F1 {};
class E4 extends E3 {};             class F4 extends F1 {};
class E5 extends E3 {};

Figure 29: The two exception families declared above. Two independent subtrees under Exception - no E is ever an F, which is why an F-typed catch clause can never claim an E and vice versa. E1 has two children and E3 two grandchildren; F1 has three children and no depth. Each connector ends in a single solid arrowhead at the parent’s bottom edge, so the arrows run from subclass to superclass.

Every one of these nine classes descends from Exception and none from RuntimeException, so all nine are checked exceptions — which is what makes the throws questions at the end of each exercise worth asking at all. The two rules the questions test are both readable off Figure 75:

  1. catch (T e) claims a thrown object if T is that object’s class or any ancestor of it — so a catch high in the tree swallows everything beneath it.
  2. catch clauses are tried in source order, and the first match wins. Order therefore matters whenever one clause’s type sits above another’s in the tree.

The code that follows is intended to illustrate concepts. Some details (for example, class declarations) are omitted. In all exercises, x and y are member variables.

On the HTML site, fill in each blank with your answer (as a quoted string, in the form x, y, e.g. "12, 20"), 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

x and y are member variables, both starting at 0:

int x = 0, y = 0;
public void exercise1() {
    try {
        try {
            f();
            y += 10;
        } catch (F3 e) {
            x += 1;
        } catch (F1 e) {
            x += 10;
        } catch (F4 e) {
            x += 100;
        } catch (E5 e) {
            y += 1;
            throw e;
        } finally {
            x += 2;
        }
        y += 20;
    } catch (Exception e) {
        y += 100;
    }
}

What are x, y after exercise1() is called, if f() throws each of the following?

f() throws F2 →

f() throws F3 →

f() throws F4 →

f() throws E4 →

f() throws E5 →

Figure 30: Exercise 1’s structure with each thrown type routed to the clause that actually claims it, and the outcome labelled beside each clause. The three things to read off it: catch (F1) sits above catch (F4) in source order and so claims F4 before that clause is ever reached; finally runs on every one of the five paths; and the two throws that leave the inner try - the unmatched E4 and the rethrown E5 - are the ones that skip y += 20 on the way to the outer handler.

  • F2 → not F3, not F4, not E5, but is an F1 (F2 extends F1), so catch (F1 e): x += 10. finally always runs: x += 2 → x = 12. Nothing escapes the inner try, so y += 20 still runs → y = 20.
  • F3 → matched directly by catch (F3 e): x += 1; finally: x += 2 → x = 3; y += 20 runs → y = 20.
  • F4 → this is the ordering trap. catch (F1 e) comes first in source order and F4 extends F1, so the F1 clause claims it and catch (F4 e) never runs: x += 10, finally x += 2 → x = 12, y += 20 → y = 20. Identical to the F2 answer, for the same reason.
  • E4 → nothing in the inner try matches. F3/F1/F4 are the other family entirely, and E5 is E4’s sibling, not an ancestor (both hang off E3). Only finally runs — x += 2 → x = 2 — and the exception keeps propagating, skipping y += 20, into catch (Exception e): y += 100 → y = 100.
  • E5 → matched by catch (E5 e): y += 1, then re-thrown. finally still runs on the way out: x += 2 → x = 2. The rethrow escapes the inner try entirely (so y += 20 is skipped — a rethrow from a catch is not offered to that same try’s other clauses) and lands in the outer catch (Exception e): y += 100 → y = 1 + 100 = 101.

Does exercise1 need a throws declaration? No. All the exceptions thrown by f() are caught either by the inner try or by the outer try, and the re-thrown exception is caught by the outer try. If all thrown exceptions are handled by a try/catch then a throws declaration is not required. The outer catch (Exception e) is what guarantees this — it sits at the root of Figure 75 and therefore claims anything at all.

CautionThis exercise would not compile as written

The exercise is a paper trace only. catch (F1 e) followed by catch (F4 e) is a compile-time error in Java, not merely a dead branch — javac reports “exception F4 has already been caught” whenever a preceding clause’s type is a superclass of a later clause’s. So the F4 answer is testing the rule (first matching clause wins, subclasses must be caught before superclasses) rather than describing code you could run. The same reasoning is what makes catch (Exception e) legal only as the last clause of a chain.

Question 2 — bonus

int x = 0, y = 0;
public void exercise2() throws ... {
    try {
        y += g();
    } catch (E3 e) {
        x += 100;
    }
}

public int g() throws ... {
    try {
        f();
        y += 10;
        return 400;
    } catch (E1 e) {
        x += 1;
    } finally {
        x += 10;
    }
    return 1;
}

f() throws E1 →

f() throws E2 →

f() throws E3 →

All three inputs give the same answer, x = 11, y = 1, and the reason is one line of Figure 75: E1, E2 and E3 all sit at or below E1, so g’s single catch (E1 e) claims every one of them.

Tracing g() for any of the three:

  1. f() throws, so y += 10 and return 400 are both skipped.
  2. catch (E1 e) runs: x += 1 → x = 1.
  3. finally runs: x += 10 → x = 11.
  4. Control leaves the try/catch/finally normally — the catch body has no return of its own — and reaches return 1. So g() returns 1.
  5. Back in exercise2, y += g() adds that 1 → y = 1. No exception ever escapes g, so exercise2’s catch (E3 e) never runs and x stays at 11, not 111.

The return 400 inside the try is the trap: it looks like the method’s answer but it is unreachable on every path where f() throws. On the path where f() does not throw, y += 10 runs, return 400 is evaluated, finally still executes x += 10 before the value leaves the method, and exercise2 ends at x = 10, y = 410 — finally runs on a return just as it does on a throw.

The throws declarations for the methods exercise2 and g would be different, depending on which type of exception f() is throwing. That is why both signatures are written as throws ... — the declaration is a function of f’s, and f’s is deliberately left unspecified.

Question 3 — bonus

g() throws F2 (unconditionally, when called):

int x = 0, y = 0;
public void exercise3() throws ... {
    try {
        try {
            try {
                f();
                x += 100;
            } catch (F2 e) {
                x += 5;
                g();
            } catch (F1 e) {
                x += 1;
            } catch (E1 e) {
                y += 2;
                throw e;
            }
            y += 10;
        } catch (F2 f) {
            y += 100;
        }
    } catch (Exception e) {
        x += 1000;
    }
}

f() throws F3 →

f() throws F2 →

f() throws E1 →

f() throws F1 →

x += 100 sits inside the innermost try, immediately after f() — so on every one of these four inputs it is skipped.

  • F3 → catch (F2 e) does not match (F3 is F2’s sibling, not its descendant); catch (F1 e) does: x += 1. Nothing further is thrown, so y += 10 runs and neither outer handler fires → x = 1, y = 10.
  • F2 → catch (F2 e) matches: x += 5, then it calls g(), which throws F2. A throw from inside a catch body is not offered to that same try’s remaining clauses — it propagates outward. It skips y += 10 and lands in the middle catch (F2 f): y += 100 → x = 5, y = 100.
  • E1 → neither F clause matches, catch (E1 e) does: y += 2, then rethrows. An E1 is not an F2, so the middle handler passes; the outermost catch (Exception e) claims it: x += 1000 → x = 1000, y = 2.
  • F1 → an F1 is not an F2 (the subclass relation only runs downward), so the first clause passes and catch (F1 e) takes it: x += 1, y += 10 runs → x = 1, y = 10. Same answer as F3, because both reach the same handler.

The pair of F2 cases is the one to take away: throwing F2 into a try whose own first clause is catch (F2 e) gets caught there, but throwing F2 from inside that clause escapes to the next try out. Two identical exception types, two completely different destinations, decided by where the throw happens rather than what is thrown.

Week 6

Refactoring

See csse2002 for course logistics.

Week 6 is one lecture in three parts: Refactoring, Cohesion and Coupling (Part 02), and SOLID Principles (Part 03).

Outline

  1. Good Practice Refactoring, When to Refactor, Code Smells
  2. Cohesion and Coupling
  3. SOLID Principles

Where refactoring sits in the development loop

Refactoring is one step in the development cycle, and the cycle is the argument for the whole topic: refactoring is a step you take only from a passing test, and it is a step you take every time round, not a clean-up project scheduled for later.

Figure 31: The development cycle. Write Test → Test Fails → Write Code → Test Passes → Refactor → back to Write Test. Refactoring is entered only from a green test and exited into writing the next test, which is why ‘have good tests before you begin’ is the second rule of good practice. The red and green washes mark the two test verdicts.

See java-testing and java-junit for the test half of that loop.

Refactoring

See java-refactoring — what refactoring is, why it’s needed, good practice, the two triggers (making a feature easier to add, and making code easier to understand), and code smells (bad naming, duplication, feature envy). Practised further in week9-lab-refactoring.

Cohesion and coupling

See java-cohesion-and-coupling — modularization, the levels of coupling (content → data) and cohesion (coincidental → functional), four worked coupling examples and two worked cohesion examples, and why high cohesion + low coupling is the goal. Practised further in week10-tutorial-coupling-and-cohesion.

SOLID principles

See java-solid-principles — why large software becomes rigid/fragile, and the first two SOLID principles: Single Responsibility and Open-Closed. The remaining three (Liskov Substitution, Interface Segregation, Dependency Inversion) are covered in 2026-04-16-solid-principles-ii.

Key takeaways

  • Refactoring is a continuous process, not a one-off tidy-up.
  • We need highly cohesive and loosely coupled classes.
  • SOLID principles are guidelines, not rules:
    • a class should have only one reason to change;
    • components should be open for extension but closed for modification.

Homework

  • SRP and memory management — check whether SRP improves memory management indirectly, by improving the overall design structure. Think about object creation, immutability and garbage collection. See java-mutability.

Week 7

SOLID Principles II

See csse2002 for course logistics. Continues 2026-04-02-refactoring (Week 6), which has Single Responsibility and Open-Closed. The remaining three SOLID principles are below. The code-level treatment of all five is in java-solid-principles.

Outline

  1. Liskov Substitution Principle (and substitution with contracts)
  2. Interface Segregation Principle
  3. Dependency Inversion Principle

Why SOLID (recap)

Large software tends towards becoming rigid and fragile.

  • Rigid software — difficult to change. Changes, even small changes, require many modifications in many parts of the codebase.
  • Fragile software — likely to break when a change is made. Sometimes the breakage occurs in parts of the codebase that appear to have no relation to the change.

SOLID principles are a way to help prevent rigidity and fragility. Many of them were floating around before becoming “SOLID”; Robert Martin combined them in Design Principles and Design Patterns (2000).

Principle Notes
S Single Responsibility Week 6 — 2026-04-02-refactoring
O Open-closed Principle Week 6 — 2026-04-02-refactoring
L Liskov Substitution Principle Week 7 — below
I Interface Segregation Principle Week 7 — below
D Dependency Inversion Week 7 — below

Liskov Substitution Principle

Subclasses should be substitutable for their parent classes.

Defined by Barbara Liskov in a 1987 keynote. In full: an instance of a subclass type can be used wherever an instance of a superclass type is expected, without breaking the correctness of the program. That last clause is the whole content of the principle.

The motivating example is an Animal supertype with Cat and Mouse subclasses, each declaring + eat(f: Food) : void, and a client that only ever talks to the supertype (see java-polymorphism, java-inheritance):

List<Animal> animals = new ArrayList<>();
animals.add(new Cat());
animals.add(new Mouse());
for (Animal animal : animals) {
    animal.eat(new Food());
}

A violation: the postgraduate GPA

Different types of students (undergraduates and postgraduates) should behave consistently when calculating GPA.

class Student {
    protected List<Course> courses;

    public double calculateGPA() {
        double totalPoints = 0;
        for (Course course : courses) {
            totalPoints += course.getGradePoints();
        }
        return totalPoints / courses.size();
    }
}

class PostgraduateStudent extends Student {
    @Override
    public double calculateGPA() {
        throw new UnsupportedOperationException("Postgraduates have a different GPA system.");
    }
}

The failure is entirely in the client code:

Student undergraduate = new UndergraduateStudent();
double gpa = undergraduate.calculateGPA();

Student postgraduate = new PostgraduateStudent();
// This will throw an exception!
gpa = postgraduate.calculateGPA();

Both variables are declared Student. The second one is not usable where a Student is expected, so PostgraduateStudent is not a substitutable subclass. This compiles perfectly and only breaks at run time — see java-exceptions.

Substitution with contracts

Substitutability is made precise using the method’s contract (see java-specification):

class Parent {
    /**
     * @requires x > 0
     * @ensures \result > 'A' && \result < 'Z'
     */
    char f(int x);
}

A subclass of Parent can override f. Even when the implementation changes, the override must still follow the contract commitments of the original version.

Note

The course spells these tags two ways: @requires / @ensures as above, and @require / @ensure (no trailing s) as in the examples further down. The Week 4 tag table and the exam preparation both use @requires / @ensures. Neither spelling is “the” course form — see csse2002-diagram-notation.

Preconditions

Suppose Child extends Parent, but Child.f() can deal with negative numbers as well. What should the precondition of Child.f() be? There are two options:

  1. Leave it as x > 0.
  2. Change it to x != 0.

A possible problem with option 1 is confusion for readers about why the limitation is there when the code is more capable.

Option 2 does not violate the substitution principle. Compare the sets of inputs each precondition allows. Everything in the first set (x > 0) is also in the second set (x != 0), so the second precondition is weaker, that is, less strict. It does not reject any state the first one would allow. Stated as an implication:

x > 0 \(\Rightarrow\) x != 0

Preconditions in a subclass must be no stronger than those in the superclass; they may be weaker or remain the same.

Postconditions

What if Child.f() only returned 'K', 'L', or 'M' — would \result > 'J' && \result < 'N' be an acceptable postcondition?

Yes. Every result still fits within the original postcondition, so the new postcondition is stronger (more restrictive). Stated as an implication, the Child postcondition implies the Parent postcondition:

\result > 'J' && \result < 'N' \(\Rightarrow\) \result > 'A' && \result < 'Z'

Postconditions in a subclass must be no weaker than those in the superclass; they may be stronger or remain the same.

The rule

A subclass must not strengthen preconditions or weaken postconditions.

The implications run in opposite directions: for preconditions the parent’s condition implies the child’s; for postconditions the child’s implies the parent’s.

The funnel picture

The rule can be drawn as well as stated. A method is a box; the cone above it is the set of inputs it will accept, the cone below is the set of outcomes it may produce. Width means permissiveness, so a wide top is a weak precondition and a wide bottom is a weak postcondition.

Figure 32: A method’s contract drawn as a funnel. The cone above A.f is the set of inputs it accepts — its precondition; the cone below is the set of outcomes it may produce — its postcondition. A wider mouth is a weaker condition, so the legal override B.f has a wider top (weaker precondition) and a narrower bottom (stronger postcondition).

Superimposing the two funnels turns the rule into a containment statement:

Figure 33: The same two funnels superimposed, the parent A.f solid and the child B.f dashed: the child’s precondition mouth contains the parent’s, and the parent’s postcondition mouth contains the child’s. The child should accept all inputs the parent accepts, and it should still guarantee outputs that satisfy everything the parent guarantees.

Worked example: One and Two

The question. Does Two satisfy the substitution principle with respect to One?

class One {
    /**
     * @require row != null && col != null && 0 < val && val < 100
     * @ensure \result is the list of all of the positive
     *     integers n < val that appear in either row or col
     */
    public List<Integer> calc(int[] row, int[] col, int val) {
    }
}

class Two extends One {
    /**
     * @require row != null && col != null && 0 < val &&
     *       val < 100 && row only contains positive integers
     * @ensure \result is the list of all of the positive
     *     integers n < val that appear in either row and col
     */
    @Override
    public List<Integer> calc(int[] row, int[] col, int val) {
    }
}

The answer. Read Two’s @ensure as “either row or col” (identical to One’s), so that the only thing left differing is the precondition. The input sets each precondition admits are:

Class One Class Two
row …, -1, 0, 1, 2, 3 … 1, 2, 3, …
col …, -1, 0, 1, … …, -1, 0, 1, …
val 1, 2, 3, 4, …, 99 1, 2, 3, 4, …, 99

col and val admit exactly the same values in both. row does not: One accepts any integers, Two accepts only positive ones. So there are inputs One would accept that Two rejects — One’s precondition does not imply Two’s. That is a strengthened precondition, and it breaks substitutability: client code written against One that happens to pass a row containing a negative number would break the moment a Two were substituted in.

Reading it off Figure 32: Two.calc’s top mouth is narrower than One.calc’s, which is exactly the shape the rule forbids.

A variant (homework). Remove && val < 100 && row only contains positive integers from Two’s precondition and change its postcondition to the integers appearing in BOTH row and col, leaving:

class Two extends One {
    /**
     * @require row != null && col != null && 0 < val
     * @ensure \result is the list of all of the positive
     *     integers n < val that appear in BOTH row and col
     */
    @Override
    public List<Integer> calc(int[] row, int[] col, int val) {
    }
}

val < 100 is gone as well, so Two’s precondition is now weaker than One’s, not equal to it. That is allowed, so the precondition side is settled. The question left is entirely about the postcondition: does that satisfy the substitution principle?

One promises the union — the positive integers below val appearing in row or col. Two now promises the intersection — those appearing in both. Take row = [1, 2], col = [2, 3], val = 10: One must return [1, 2, 3], Two returns [2]. Both postconditions pin the result down to a single list, and those lists differ, so Two’s postcondition does not imply One’s. Since the rule demands exactly that implication, it fails and LSP is violated. (The two are in fact incomparable — neither implies the other — which is still a failure, because “no weaker” means “implies”.)

In funnel terms: Two.calc’s bottom mouth is not contained in One.calc’s; it juts outside it, and containment is what the rule demands. Client code that relied on One’s promise — say, looking up 3 in the returned list — silently gets a wrong answer rather than an exception, which is the fragility SOLID exists to prevent.

This example is drilled again in week9-tutorial-substitution-principle-and-pre-post-conditions.

Interface Segregation Principle

Many client specific interfaces are better than one general purpose interface.

ISP builds on coupling — the degree of interdependence between modules, classes or components — and its seven levels from Content (tightly coupled, “needy”) down to None (loosely coupled, “independent”). The levels are from Week 6: see java-cohesion-and-coupling for the levels and worked classifications, and week10-tutorial-coupling-and-cohesion for the applied class.

The bridge from coupling to ISP is the class R example and its risk of causing incidental dependencies:

public class R {
    int x, y, z;
    char a, b, c;
}

public static void compute(R r) {
    return r.x * r.y;
}

public static void run() {
    R r = new R(1, 2, 3, 'a', 'b', 'c');
    compute(r);
}

compute is handed the whole of R but only reads two of its six fields (stamp coupling). ISP is that observation applied to a type’s public surface:

  • Shrink interfaces to minimize incidental dependencies.
  • Larger interfaces should be split into smaller ones, to ensure that implementing classes only need to be concerned about the methods that are of interest to them.

The problem

Figure 34: Despite only using a small subset of Z, each class inadvertently depends on all of Z. A node is a rectangle labelled with its Java keyword and name, with its members listed inside the same box as + a() and no compartment rule. The solid Uses arrow points from the depender to the thing depended on, and ends on the member row it uses, not on the box edge.

The cost: when Z changes, clients A, B, and C may all be affected, even if each uses only a small part of Z, so they may need to be recompiled and redeployed.

The solution

Figure 35: Create interfaces to minimize the incidental dependencies: A now depends only on AI, B only on BI, C only on CI, and Z implements all three. A solid line is Uses and a dashed line is Implements, both pointing from the depender to the thing depended on. Both have the same filled arrowhead, so only the line style tells them apart. The interfaces are named AI/BI/CI here and BSpec in the dependency inversion figure; the course does not settle on one naming scheme.

Z is unchanged — it still has all five methods. What changed is that no client can see more of Z than it needs, so a change to d() can no longer force A or B to be recompiled.

Dependency Inversion Principle

Depend upon Abstractions. Do not depend upon concretions.

Entities must depend on abstractions, not on concretions. The high-level module must not depend on the low-level module; both should depend on abstractions.

Figure 36: Inverting a dependency. In (a) A depends directly on the concrete B, so changes in the implementation can propagate to A. In (b) A depends only on BSpec, so changes inside B are less likely to affect A as long as BSpec stays the same. The edge from A to BSpec in (b) is drawn dashed, the Implements style, even though A merely uses BSpec.

The cheapest version: program to the interface you already have

The first DIP example changes one type name, in three places. Before:

public static void main(String[] args) {
    ArrayList<Course> courses = new ArrayList<>();
    Student student = new Student(courses);
    double totalGradePoints = student.calculateTotalGradePoints();
}

class Student {
    private ArrayList<Course> courses;
    public Student(ArrayList<Course> courses) { this.courses = courses; }

    public double calculateTotalGradePoints() {
        return totalGradePoints;
    }
}

After: every ArrayList in a declared type position becomes List, while new ArrayList<>() is left alone. The constructor call is the one place a concrete class has to be named.

public static void main(String[] args) {
    List<Course> courses = new ArrayList<>();
    Student student = new Student(courses);
    double totalGradePoints = student.calculateTotalGradePoints();
}

class Student {
    private List<Course> courses;
    public Student(List<Course> courses) { this.courses = courses; }

    public double calculateTotalGradePoints() {
        return totalGradePoints;
    }
}

See java-collections-framework for the List/ArrayList split this relies on, and java-abstraction.

Dependency Injection

Dependency Injection (DI) is a design pattern that implements the Dependency Inversion Principle (DIP), by injecting dependencies into a class instead of creating them internally, promoting loose coupling.

In the Student code above, the Student object receives its dependency through the constructor. The dependency is created in main and handed in — Student never calls new on it.

The full example runs the same move on a service that creates its own collaborator:

class AlertService {
    public void sendAlert(String msg) {
        EmailSender sender = new EmailSender();
        sender.send(msg);
    }
}
  • AlertService is tightly coupled to EmailSender.
  • AlertService can only send emails.
  • AlertService creates its own dependency.

Introducing the abstraction and injecting it fixes all three:

interface MessageSender {
    void send(String msg);
}

class EmailSender implements MessageSender {
    @Override
    public void send(String msg) {
        System.out.println("Sending EMAIL: " + msg);
    }
}

class SmsSender implements MessageSender {
    @Override
    public void send(String msg) {
        System.out.println("Sending SMS: " + msg);
    }
}

class AlertService {
    private MessageSender sender;

    public AlertService(MessageSender sender) {
        this.sender = sender;
    }

    public void sendAlert(String msg) {
        sender.send(msg);
    }
}
  • AlertService no longer depends directly on EmailSender.
  • It depends on the interface MessageSender.
  • The actual sender is injected from outside.

Stability, exposure, and the “proper” form of DIP (creating an abstraction where none exists yet) are worked through in java-solid-principles and drilled in week11-tutorial-dependency-inversion.

Summary and key takeaways

The takeaways for the whole block, not only this lecture:

Further reading

Applied class

No separate applied-class topic on SOLID this week — see week7-tutorial-black-box-and-glass-box-testing for this week’s applied class (black-box/glass-box testing, a continuation of java-testing from Week 5).

Black-box and Glass-box Testing

Applied class for 2026-04-16-solid-principles-ii (Week 7). Applies the black-box/white-box testing concepts from java-testing (Week 5, 2026-03-26-testing) to a worked example. Most of these tasks ask for a set of inputs achieving some coverage goal — many different answers are equally correct, so answers here are reveal-only worked examples rather than checkable exercises.

1. Black box testing

The following class tracks how many passengers are on a bus. Only the specification is given — no bodies — because black-box tests are written against the specification, not the implementation.

public class Bus {
    /**
     * Construct a new instance of the bus with a specified capacity.
     *
     * @param capacity The maximum passengers at any one time.
     */
    public Bus(int capacity) {...}

    /**
     * Calculate how many passengers are currently on the bus.
     *
     * @returns The number of passengers on the bus.
     */
    public int getCurrent() {...}

    /**
     * Calculate the average number of passengers on the bus between stops.
     *
     * @returns The average passengers on the bus.
     */
    public int getAverageCount() {...}

    /**
     * Exchange passengers at a bus stop.
     * Passengers get off before new passengers get on.
     *
     * @param on The number of passengers boarding the bus.
     * @param off The number of passengers disembarking the bus.
     */
    public void stop(int on, int off) {...}
}

The class above spells the tag @returns, not the standard @return. The course is inconsistent about specification-tag spellings (see csse2002-diagram-notation).

Task 0 — write a smoke test

There is a huge range of smoke tests you could come up with. Your smoke test should utilize the Bus class under normal/expected operation:

Bus bus = new Bus(10);
bus.stop(5, 0);
bus.stop(3, 1);
assertEquals(7, bus.getCurrent());
assertEquals(6, bus.getAverageCount());

The Javadoc says passengers get off before new passengers get on, so stop(3, 1) on a bus holding 5 goes \(5 - 1 = 4\), then \(4 + 3 = 7\); and the average between the two stops is \((5 + 7) / 2 = 6\).

See java-junit for assertEquals and week8-lab-junit-testing for writing these as real tests.

Task 1 — develop boundary scenarios (with justification)

Develop some boundary scenarios/inputs to use for testing. For each scenario you should justify why it is a good boundary case. You are not expected to know the expected output for each scenario.

There are many different situations to try; the following are just some examples.

Scenario Justification
Construct a bus with capacity 0 A bus that can have no passengers is an uncommon scenario we may expect bugs from.
Construct a bus with a negative capacity It is not clear how a bus with a negative capacity should behave; we should aim to clarify its functionality and test it.
Ask for the average number of passengers after no stops An average often involves division by the number of times — we want to ensure that asking for the average after zero stops doesn’t create an exception.
Negative values for on and off Behaviour for negative values is unclear — will a negative number of on passengers result in passengers getting off?
More passengers get off at the stop than are currently on the bus Results in undefined behaviour.
More passengers on the bus than capacity Behaviour is not specified, so we wish to see how Bus behaves.

Task 2 — how can we make Bus’s behaviour fully specified?

Many of the boundary scenarios/inputs above are a result of unspecified or unclear behaviour of the bus class. How can we fix Bus to make all behaviour specified and clear?

If we specify that getCurrent() <= capacity is an invariant of the Bus class (see java-specification), then we must protect the invariant throughout by either throwing exceptions or adding preconditions:

  1. Add a throws IllegalArgumentException to the constructor of Bus when capacity < 0.
  2. Add a precondition to stop that both on and off are greater than or equal to zero.
  3. Add a throws IllegalStateException to the stop method if getCurrent() + on - off is less than zero or greater than capacity.

The two exception types do different jobs (see java-exceptions): the argument itself is nonsense in case 1, whereas in case 3 the arguments are individually fine but would drive the object into a state the invariant forbids.

2. Glass box testing

Glass-box testing helps us cover edge cases of program control flow. This is possible as we are allowed to use the internal structure (control-flow) of a method to construct our test cases.

There are different levels of code coverage; in this course we focus on three:

  1. Statement coverage
  2. Branch coverage
  3. Path coverage

Consider what inputs would achieve each level of code coverage for countOccurrences:

public static int countOccurrences(int[] array, int target) {
    int count = 0;
    for (int num : array) {
        if (num == target) {
            count++;
        }
    }
    return count;
}
  • Statement coverage — every statement must run at least once, and the only one that isn’t run unconditionally is count++. So the array must contain the target at least once: [2] with target 2.
  • Branch coverage — the if must additionally be false once, and the for must additionally terminate (it always does). [2, 3] with target 2 is enough on its own; so is [2, 3, 2].
  • Path coverage — approximated as 0, 1 and 2 iterations crossed with the if outcome each time, exactly the seven-row shape used for ascending. Because there is no early return, all seven are reachable.

3. Ascending

/**
 * Returns true if and only if numbers is an array of ascending
 * integers.
 *
 * @require numbers != null
 * @ensure \result is true iff for all indices j such that
 * 0 <= j < numbers.length - 1, numbers[j] <= numbers[j + 1]
 */
public boolean ascending(int[] numbers) {
    boolean result = true;
    for (int i = 0; i < numbers.length - 1; i++) {
        // invariant: for all j, 0 <= j < i, numbers[j] <= numbers[j + 1]
        if (numbers[i] > numbers[i + 1]) {
            result = false;
        }
    }
    return result;
}

The // invariant: line is the loop invariant — see java-loop-invariants. It plays no part in the coverage answers below, which turn on the loop’s shape: the body has no early exit, so every combination of iteration count and if outcome is reachable.

The three coverage levels are questions about the method’s control-flow graph, so it helps to have it in front of you:

Figure 37: Control-flow graph of ascending. Every statement lies on some path; the two labelled edges out of numbers[i] > numbers[i + 1] are the only branch in the loop body, and the back edge is what makes exhaustive path coverage infeasible and forces the 0/1/2-iteration approximation. Statements and decisions are both drawn as plain rectangles; the teal arrows are the flow of control.

Task 3 — statement coverage

Provide a minimal set of inputs that achieve statement coverage.

[2, 1]

One iteration, with the if true, is enough to touch result = false — the only statement not on the unconditional path.

Task 4 — branch coverage

Provide a minimal set of inputs that achieve branch coverage.

[2, 1, 2] or the pair [2, 1] [1, 2]

Either way the if has to come out true once and false once.

Task 5 — path coverage

Provide a minimal set of inputs that achieve path coverage.

Input Justification
[] or [3] 0 times through loop
[3, 4] 1 time through loop, if false
[4, 3] 1 time through loop, if true
[3, 4, 5] 2 times through loop, if false, false
[3, 4, 2] 2 times through loop, if false, true
[4, 3, 5] 2 times through loop, if true, false
[5, 4, 3] 2 times through loop, if true, true

Writing the justification for each row helps ensure no cases are missed.

Both [] and [3] give zero iterations, because the loop bound is numbers.length - 1. The 0/1/2-iteration approximation is the one from java-testing — exhaustive path coverage of a loop is infeasible.

4. Maximum — bonus

Returns the maximum number within an array of integers, if one exists, else returns Integer.MIN_VALUE.

/**
 * Returns the maximum number within an array of integer,
 * if one exists, else returns Integer.MIN_VALUE.
 *
 * @require numbers != null
 * @ensure numbers.length > 0 ==> (
 *     (\forall int i; 0 <= i < numbers.length ==> \result >= numbers[i]) &&
 *     (\exists int i; 0 <= i < numbers.length && \result == numbers[i])
 * )
 * @ensure numbers.length == 0 ==> \result = Integer.MIN_VALUE
 */
public int maximum(int[] numbers) {
    int currentMaximum = Integer.MIN_VALUE;
    for (int number : numbers) {
        if (number > currentMaximum) {
            currentMaximum = number;
        }
    }
    return currentMaximum;
}

Task 6 — statement coverage

[1]

Task 7 — branch coverage

[2, 1]

The first element beats Integer.MIN_VALUE (if true), the second does not beat 2 (if false).

Task 8 — path coverage

Input Justification
[] 0 times through loop
[Integer.MIN_VALUE] 1 time through loop, if false
[1] 1 time through loop, if true
[Integer.MIN_VALUE, Integer.MIN_VALUE] 2 times through loop, if false, false
[Integer.MIN_VALUE, 1] 2 times through loop, if false, true
[2, 1] 2 times through loop, if true, false
[1, 2] 2 times through loop, if true, true

Integer.MIN_VALUE is doing real work here: it is the only value for which number > currentMaximum can be false on the first iteration, because the accumulator starts there and the comparison is strict.

5. Index Of — bonus

/**
 * Returns the index of the given number within the array of numbers,
 * or -1 if number is not in numbers.
 *
 * @require numbers != null
 * @ensure numbers[\result] = number ||
 *     (\result == -1 &&
 *      \forall int j; 0 <= j < numbers.length ==> numbers[j] != number)
 */
public int indexOf(int[] numbers, int number) {
    for (int i = 0; i < numbers.length; i++) {
        // invariant: \forall int j; 0 <= j < i ==> numbers[j] != number
        if (numbers[i] == number) {
            return i;
        }
    }
    return -1;
}

This one differs from the other two in exactly one structural way: the if body returns, so the true branch leaves the method instead of continuing round the loop.

Figure 38: Control-flow graph of indexOf. Unlike ascending, the true branch of the if is an exit, not a step — so no path can take the if true and then iterate again, which is why two of the seven path-coverage rows in Task 11 read Cannot be tested. The exit is labelled in magenta.

Task 9 — statement coverage

[] 1 and [1] 1

Two calls are needed: return i and return -1 are both statements, and no single input reaches both.

Task 10 — branch coverage

[] 1 and [2, 1] 1

[2, 1] with target 1 takes the if false then true; [] takes the loop condition false immediately.

Task 11 — path coverage

Input Justification
[] 42 0 times through loop
[1] 2 1 time through loop, if false
[1] 1 1 time through loop, if true
[1, 2] 3 2 times through loop, if false, false
[1, 2] 2 2 times through loop, if false, true
Cannot be tested. 2 times through loop, if true, false
Cannot be tested. 2 times through loop, if true, true

The last two rows are unreachable for the reason drawn in Figure 38: taking the if true on the first iteration returns immediately, so there is no second iteration to have an outcome at all.

Week 8

Java I/O

See csse2002 for course logistics.

Topics

  1. Streams (java.io, since Java 1.0) — byte-oriented
  2. Readers & Writers (java.io, since Java 1.1) — character-oriented
  3. Scanner (java.util, since Java 1.5) — a convenience wrapper, neither stream nor reader
  4. New I/O (java.nio.file, since Java 1.7) — the file system itself

Instance Saving & Loading — saving and loading an object model to a file — is taken up in the Week 10 practical, week10-lab-java-io.

All content is in java-io.

The thread running through it

Each generation of the API is a response to what the previous one was awkward at:

  • Byte streams give one uniform abstraction over any source or destination, so a method can take an OutputStream and not care whether it is a console, a file, or an array (see java-solid-principles — Liskov Substitution).
  • They were never ideal for text, so Readers & Writers were added to work in chars and Unicode. InputStreamReader is the bridge back to the byte world.
  • Everything in java.io is assembled by wrapping one object around another — buffering, line-reading and formatting are separate classes you stack, not options on one class.
  • None of it was designed for managing files and directories, so New I/O adds Path and Files.
  • Every stream and reader must be closed; try-with-resources is the way to do it (Effective Java Item 9). This is where the topic leans hardest on java-exceptions.

Summary — which to use? Streams for binary data, Readers & Writers for text, New I/O when manipulating a file system or file contents.

Set as homework

Applied class

See week8-tutorial-class-invariants — protecting class invariants (a continuation of java-specification and java-encapsulation from earlier weeks).

Practical

See week8-lab-junit-testing — Test Driven Development with JUnit, extending java-junit from Week 5.

JUnit Testing

Practical for 2026-04-23-java-io (Week 8). Extends java-junit (Week 5) with a full Test Driven Development (TDD) worked example.

Test Driven Development (TDD)

Cycle (see java-testing):

  1. Write a test for some piece of functionality.
  2. Write just enough functionality for the test to pass.
  3. Refactor implementation while preserving the passing test.
  4. Repeat.

Step 3’s refactoring can be of the implementation under test or of the test code itself.

Stubs: a stub class has all public members, but methods return dummy values based on their return type — void methods are empty, primitives return a ‘default’ value such as 0 for integers, reference types normally return null. This lets you write an outline of a class that compiles but may not work.

In pure test driven development, not compiling is considered a test failure, so a test is written for a class before it exists, and creating the class is considered a part of making a test pass.

DistinctCounter

Tracks a collection of distinct strings, which may be added to the collection and retrieved in lexicographical order:

  • DistinctCounter()
  • void add(String element)
  • int getDistinctCount()
  • String[] getStrings() — in lexicographical order
DistinctCounter distinct = new DistinctCounter();
distinct.add("Z");
distinct.add("Hello");
distinct.add("Z");
distinct.add("Hello ");
distinct.getDistinctCount(); // 3
distinct.getStrings();       // {"Hello", "Hello ", "Z"}

"Hello" and "Hello " are distinct — the trailing space matters — and "Hello " sorts before "Z".

Task 0 — the stub

class DistinctCounter {
    public DistinctCounter() {}
    void add(String element) {}
    int getDistinctCount() {
        return 0;
    }
    String[] getStrings() {
        return null;
    }
}

Task 1 — the JUnit 4 test class

import org.junit.Test;

import static org.junit.Assert.*;

class DistinctCounterTest {
    @Test
    public void testEmpty() {}
}

Task 2 — the test cases

Write each of the following, and after each one write just enough code to make it pass, then refactor. The count cases:

  1. An empty counter has a distinct count of zero.
  2. A counter with one element has a count of one.
  3. A counter with two distinct elements has only a count of two.
  4. A counter with two identical elements has a count of one.
  5. A counter with two identical elements and one other unique element has a count of two.
  6. A counter with N distinct elements has a counter of N for N > 4.

The array cases mirror those six, plus three extra cases that ask specifically for a sorted array:

  1. An empty counter has an empty array of strings.
  2. A counter with one element has an array with that element.
  3. A counter with two distinct elements has an array of those two elements.
  4. A counter with two distinct elements has a sorted array of those two elements.
  5. A counter with two identical elements has an array of one element.
  6. A counter with two identical elements and one other unique element has an array of two elements.
  7. A counter with two identical elements and one other unique element has a sorted array of two elements.
  8. A counter with N distinct elements has an array of N elements for N > 4.
  9. A counter with N distinct elements has a sorted array of N elements for N > 4.

There are many different ways to implement DistinctCounter, so it becomes an interface with four different implementations behind it — which is exactly the point of writing the tests first: all four pass the same fifteen cases of Task 2.

public interface DistinctCounter {
    void add(String value);
    int getDistinctCount();
    String[] getStrings();
}

1 — a hash set. A set won’t add duplicates, so add is trivial and the sorting happens on the way out:

public class DistinctCounterHashSet implements DistinctCounter {
    private final Set<String> distinct;

    public DistinctCounterHashSet() {
        distinct = new HashSet<>();
    }

    public void add(String word) {
        // set won't add duplicates
        distinct.add(word);
    }

    public int getDistinctCount() {
        return distinct.size();
    }

    public String[] getStrings() {
        String[] elements = new String[distinct.size()];
        int index = 0;
        for (String element : distinct) {
            elements[index] = element;
            index++;
        }
        Arrays.sort(elements);
        return elements;
    }
}

2 — a tree set, which automatically keeps elements in sorted order, so getStrings() needs no Arrays.sort at all:

public class DistinctCounterTreeSet implements DistinctCounter {
    /** TreeSet maintains Strings in lexicographical order **/
    private final Set<String> distinct;

    public DistinctCounterTreeSet() {
        distinct = new TreeSet<>();
    }

    public void add(String word) {
        // set won't add duplicates
        distinct.add(word);
    }

    public int getDistinctCount() {
        return distinct.size();
    }

    public String[] getStrings() {
        return distinct.toArray(new String[]{});
    }
}

3 — an array list, sorted on get. Without a set, add must check contains itself:

public class DistinctCounterArrayListOnGet implements DistinctCounter {
    private final List<String> distinct;

    public DistinctCounterArrayListOnGet() {
        distinct = new ArrayList<>();
    }

    public void add(String word) {
        if (distinct.contains(word)) {
            return;
        }
        distinct.add(word);
    }

    public int getDistinctCount() {
        return distinct.size();
    }

    public String[] getStrings() {
        String[] elements = distinct.toArray(new String[]{});
        Arrays.sort(elements);
        return elements;
    }
}

4 — DistinctCounterArrayListOnAdd, an array list sorted on add — an insertion sort, walking to the first element that sorts after word and inserting there; if no such element exists, word sorts after everything already in the list and is appended. Because the list is already ordered, this class’s getStrings() is the bare return distinct.toArray(new String[]{}); — no Arrays.sort, unlike implementation 3. Only add is given here:

public void add(String word) {
    if (distinct.contains(word)) {
        return;
    }
    boolean added = false;
    for (int i = 0; i < distinct.size(); i++) {
        if (distinct.get(i).compareTo(word) > 0) {
            distinct.add(i, word);
            added = true;
            break;
        }
    }
    if (!added) {
        distinct.add(word);
    }
}

The tests. @Before constructs an instance of DistinctCounter rather than duplicating the creation in every test method. The new DistinctCounter() in setup() below no longer compiles once DistinctCounter is the interface; in practice you construct whichever of the four implementations you are testing.

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class DistinctCounterTest {
    private DistinctCounter counter;

    @Before
    public void setup() {
        counter = new DistinctCounter();
    }
    ...
}

Some insist that each test method should have only one assertion. The tests here do that because it corresponds to the test cases listed for the exercise, but it is better to refactor tests to have two assertions than to duplicate the initialisation code.

That gives twelve test methods, not fifteen. The six count cases map one-to-one, but the nine array cases collapse to six methods, because each “…has a sorted array of…” case is already pinned down by the expected array in the case above it.

@Test
public void testEmptyCounterCount() {
    assertEquals("Empty counter does not have a count of zero",
            0, counter.getDistinctCount());
}

@Test
public void testTwoIdenticalCount() {
    counter.add("A");
    counter.add("A");
    assertEquals("Counter with two identical elements does not have count of one",
            1, counter.getDistinctCount());
}

@Test
public void testEmptyArray() {
    assertArrayEquals("Empty counter does not have an empty array",
            new String[]{}, counter.getStrings());
}

@Test
public void testTwoDistinctArray() {
    counter.add("A");
    counter.add("B");
    assertArrayEquals("Counter with two distinct elements does not have an array of two",
            new String[]{"A", "B"}, counter.getStrings());
}

@Test
public void testNDinstinctElementsArray() {
    counter.add("E"); counter.add("A"); counter.add("B"); counter.add("A");
    counter.add("A"); counter.add("B"); counter.add("D"); counter.add("A");
    counter.add("A"); counter.add("C"); counter.add("B");
    assertArrayEquals("Counter with 5 distinct elements does not have an array of five",
            new String[]{"A", "B", "C", "D", "E"}, counter.getStrings());
}

In the last one the elements are added deliberately out of order and with repeats, so the expected array simultaneously pins down distinctness, count, and sorted order.

Four implementations, one interface, one shared test suite — and, looking ahead, one of those four is the class that PalindromeCounter actually extends:

Figure 39: The four interchangeable implementations of one DistinctCounter interface, and — below them — the one of the four that PalindromeCounter actually extends. The dashed line running from implementer to interface is the implements arrow. In the course’s dependency diagrams Uses is a solid line and Implements a dashed line, both with the same small filled arrowhead; this course does not use UML’s hollow realisation triangle. The solid teal arrow into the superclass is the generalisation (extends) connector.

Task 3 — a boundary case

Test driven development will result in a highly comprehensive test suite, with every component rigorously tested. One possible downside is that it tends to target “happy path” execution — so it is worth adding boundary cases (see java-testing) deliberately.

@Test
public void testNullStringCount() {
    counter.add(null);
    assertEquals(0, counter.getDistinctCount());
}

@Test
public void testNullStringArray() {
    counter.add(null);
    assertArrayEquals(new String[]{}, counter.getStrings());
}

The exercise asks how does your implementation handle this case? Only DistinctCounterTreeSet throws, and it throws on add itself, because a TreeSet has to compare the incoming element against what it holds. The other three accept null, so the count becomes 1 and both assertions simply fail. In particular DistinctCounterArrayListOnAdd never reaches compareTo here — on a fresh counter the list is empty, so its insertion loop has nothing to walk and the null is appended. (It, and the two implementations that call Arrays.sort on the way out, would hit a NullPointerException on a null only once the counter already holds another element to compare against.) Deciding which behaviour is correct is a specification question, not an implementation one — see java-specification.

PalindromeCounter

PalindromeCounter inherits from DistinctCounter and extends it with:

  1. int getPalindromeCount() — number of distinct palindromes
  2. String[] getPalindromes() — distinct palindromes
  3. String[] getNonPalindromes() — distinct non-palindromes

Tasks 4 and 5 repeat Tasks 0 and 1 for this class: write the stub, then create the JUnit 4 test class, following the DistinctCounter pattern. Task 6 then builds up test cases and functionality together, TDD-style.

It extends DistinctCounterTreeSet — one concrete implementation, not the interface — which is why getStrings() is already in lexicographical order and getPalindromes() can simply filter it in place:

public class PalindromeCounter extends DistinctCounterTreeSet {

    private static boolean isPalindrome(String word) {
        if (word.length() < 2) {
            return true;
        }
        if (word.charAt(0) != word.charAt(word.length() - 1)) {
            return false;
        }
        return isPalindrome(word.substring(1, word.length() - 1));
    }

    public int getPalindromeCount() {
        return getPalindromes().length;
    }

    public String[] getPalindromes() {
        List<String> palindromes = new ArrayList<>();
        for (String word : getStrings()) {
            if (isPalindrome(word)) {
                palindromes.add(word);
            }
        }
        return palindromes.toArray(new String[]{});
    }

    public String[] getNonPalindromes() {
        // wrapping in new array list required to allow removeAll
        List<String> distincts = new ArrayList<>(Arrays.asList(getStrings()));
        List<String> palindromes = Arrays.asList(getPalindromes());
        distincts.removeAll(palindromes); // removes the palindromes
        return distincts.toArray(new String[]{});
    }
}

Two details in isPalindrome worth pinning down: a string shorter than two characters is a palindrome by definition (the recursive base case), and the comparison is case-sensitive on the characters as written — "AbbA" is a palindrome because 'A' == 'A' and 'b' == 'b', no case-folding involved.

getNonPalindromes has to wrap Arrays.asList(...) in a new ArrayList<>(...): Arrays.asList returns a fixed-size view, which does not support removeAll.

The tests, built up one case at a time — empty, a single palindrome, a single non-palindrome, one of each, then several of each. These are only a subset of the tests you could implement using test driven development; three of the five methods are given here:

public class PalindromeCounterTest {
    private PalindromeCounter counter;

    @Before
    public void setup() {
        counter = new PalindromeCounter();
    }

    @Test
    public void testEmptyCounter() {
        assertEquals("Empty counter does not have a count of zero",
                0, counter.getPalindromeCount());
        assertArrayEquals("Empty counter does not have no palindromes",
                new String[]{}, counter.getPalindromes());
        assertArrayEquals("Empty counter does not have no non palindromes",
                new String[]{}, counter.getNonPalindromes());
    }

    @Test
    public void testSingleNonPalindromeCounter() {
        counter.add("car");
        assertEquals("Counter with one non-palindrome does not have count of zero",
                0, counter.getPalindromeCount());
        assertArrayEquals("Counter with one non-palindrome does not have empty palindromes",
                new String[]{}, counter.getPalindromes());
        assertArrayEquals("Counter with one non-palindrome does not have a non-palindromes array of that element",
                new String[]{"car"}, counter.getNonPalindromes());
    }

    @Test
    public void testManyOfEachCounter() {
        counter.add("car");
        counter.add("racecar");
        counter.add("mamma mia");
        counter.add("AbbA");
        counter.add("palindrome");
        counter.add("rufus");
        assertEquals("Counter with two palindromes has incorrect count",
                2, counter.getPalindromeCount());
        assertArrayEquals("Counter with multiple palindromes does not have all in array",
                new String[]{"AbbA", "racecar"}, counter.getPalindromes());
        assertArrayEquals("Counter with multiple non-palindromes does not have all in array",
                new String[]{"car", "mamma mia", "palindrome", "rufus"}, counter.getNonPalindromes());
    }
}

These test methods carry three assertions each — the refactoring recommended for the DistinctCounter tests but not done there, now that the three getters are all views of the same added words.

Class Invariants

Applied class for 2026-04-23-java-io (Week 8). Applies java-encapsulation’s class invariants (and the preconditions/postconditions from java-specification) to worked examples.

Two failure modes run through the sheet, and it is worth naming them up front, because every fix it asks for is a response to one or the other. (The grouping is mine, not the sheet’s; Tasks 0 and 3, which only ask you to state an invariant, sit outside it.)

  1. The specification lets the invariant break. No precondition rules out the argument that would violate it.
  2. The implementation lets the invariant break, even though the specification is fine — because it hands out a reference to its own internal state (see Figure 40).

XFiles

XFiles maintains the invariant that every stored string must be prefixed with 'X':

\[\forall\, 0 \le i < \texttt{getFiles().size()} \implies \texttt{getFiles().get(i).startsWith("X")}\]

/**
 * @invariant
 *     \forall i; 0 <= i < getFiles().size(); getFiles().get(i).startsWith("X")
 */
public class XFiles {
    /**
     * @ensures getFiles().contains(newFile)
     * @ensures getFiles().size() == \old(getFiles()).size() + 1
     */
    public void add(String newFile) {...}

    /**
     * @ensures !getFiles().contains(file)
     */
    public void remove(String file) {...}

    public List<String> getFiles() {...}
}

As specified, add allows the invariant to be broken: given a string that does not start with 'X', the specification still states that the string will be included in getFiles(). Fix — failure mode (1) — add a precondition:

/**
 * @requires newFile.startsWith("X")
 */

Even with that precondition documented, a naive implementation still has two further leaks (see java-encapsulation — Protecting invariants):

public class XFiles {
    public List<String> files = new ArrayList<>(); // (1) public field

    public void add(String newFile) {
        if (newFile.startsWith("X")) {
            files.add(newFile);
        }
    }
    public void remove(String file) { files.remove(file); }

    public List<String> getFiles() {
        return files; // (2) leaks the internal reference
    }
}
  1. files is public — callers can grab the list directly and mutate it, bypassing add’s check entirely:

    List<String> secret = xFiles.files;
    secret.add("Doesn't start with X!"); // breaks the invariant

    Fix: private List<String> files;.

  2. getFiles() returns the internal reference — even with files made private, the returned list is still the real one:

    List<String> secret = xFiles.getFiles();
    secret.add("Doesn't start with X!"); // still breaks the invariant

    Fix: return a defensive copy, return new ArrayList<>(files);.

Leak (2) is failure mode (2), and it is the one worth having a picture of — the same leak, in the same shape, is the “real bug” of the Screening task below (return tickets; on a Set<Ticket> in place of return files; on a List<String>), and is drawn there in Figure 40.

Cinema and Screening

public class Cinema {
    /**
     * @ensures getCapacity() == capacity
     */
    public Cinema(int capacity) {...}
    public int getCapacity() {...}
}

A useful invariant: getCapacity() >= 0.

Precondition to preserve it: the constructor needs capacity >= 0.

/**
 * @invariant getEndTime() > getStartTime()
 */
public class Screening {
    /** @ensures \result > 946648800 */
    public int getStartTime() {...}
    /** @ensures \result > 946648800 */
    public int getEndTime() {...}
    /** @ensures getEndTime() == \old(getEndTime()) + amount */
    public int extendRuntime(int amount) {...}
}

(All times are unix timestamps — seconds since 1 January 1970. 946648800 is 1 January 2000, when the cinema opened.)

Do the methods preserve the invariant? No — the invariant may be violated if a negative amount is given to extendRuntime(int), pushing getEndTime() below (or equal to) getStartTime(). Two sensible preconditions on extendRuntime:

  1. amount >= 0
  2. getEndTime() + amount > getStartTime()

The name of the method (extendRuntime) implies the first is more likely.

Now extend Screening with ticket sales:

public class Screening {
    // getStartTime(), getEndTime(), extendRuntime(int) as before.
    public Cinema getCinema() {...}

    /**
     * @ensures getSoldTickets().contains(\result)
     * @ensures getSoldTickets().size() == \old(getSoldTickets()).size() + 1
     */
    public Ticket sellTicket() {...}

    public Set<Ticket> getSoldTickets() {...}
}

Invariant to stop the screening overselling:

/**
 * @invariant getSoldTickets().size() <= getCinema().getCapacity()
 */

Precondition to preserve it — added to sellTicket(), so we don’t sell into a full cinema:

getSoldTickets().size() < getCinema().getCapacity()

Technically, since the invariant may itself be assumed as another precondition, specifying getSoldTickets().size() != getCinema().getCapacity() is enough — that inequality and the invariant together imply the strict <.

Now consider a concrete (simplified) implementation:

public class Screening {
    private Set<Ticket> tickets = new HashSet<>();

    public Ticket sellTicket() {
        Ticket ticket = new Ticket(...);
        tickets.add(ticket);
        return ticket;
    }

    public Set<Ticket> getSoldTickets() {
        return tickets;
    }
}

Does this protect the invariant? Not really, for two reasons.

1. sellTicket() never checks its precondition. In true programming by contract that is defensible — we make no guarantees about what happens when a precondition is violated. But if sellTicket() is likely to be exposed to others, we should aim to program defensively as well as by contract (see java-specification), which improves robustness:

public Ticket sellTicket() {
    if (tickets.size() >= getCinema().getCapacity()) {
        return null;
    }
    ...
}

That protects the invariant but potentially introduces a difficult-to-track-down null bug in the calling code. A better solution:

public Ticket sellTicket() {
    if (tickets.size() >= getCinema().getCapacity()) {
        throw new IllegalArgumentException("Screening full!");
    }
    ...
}

2. The real bug is that getSoldTickets() exposes the reference to the internal tickets set, allowing the screening to become oversold without sellTicket() ever being called:

Screening screening = // screening with cinema of capacity = 100
for (int i = 0; i < 101; i++) {
    screening.getSoldTickets().add(new Ticket());
}

Fix by returning a copy:

public Set<Ticket> getSoldTickets() {
    return new HashSet<>(tickets);
}

(The solutions sheet writes this fix as public Ticket getSoldTickets() { return new ArrayList<>(tickets); } — a typo on two counts: the field is a Set<Ticket>, and the return type is Set<Ticket>, not Ticket. The intent is a defensive copy of the same collection type.)

Figure 40: Why returning the internal collection breaks an invariant that the class otherwise enforces. (a) return tickets; — the caller’s secret and the object’s own field name one set, so secret.add(...) writes straight into Screening’s state, past every check sellTicket() makes. (b) return new HashSet<>(tickets); — the caller gets its own set to mutate. Dashed box = the object’s encapsulation boundary; teal arrow = a reference. CSSE2002 establishes no notation for object/reference (boxes-and-pointers) diagrams — object diagrams, stack-and-heap diagrams and has-a relationships are all left unsettled by the course’s own materials — so this rendering is mine. Only the teal reference colour and the magenta verdict text follow the course’s own conventions.

The pattern to take away: an invariant is only as strong as the widest way in to the state it constrains. A precondition closes the front door; private closes the side door; a defensive copy closes the one left open by every getter that returns a mutable object.

Week 9

Generics in Java

See csse2002 for course logistics.

Outline

  1. Generics
  2. Bounded Generics
  3. Bounds through Wildcards
  4. Type Erasure
  5. Practical Example

Definitions, the full listings and the bookshop worked example are in java-generics. What follows is the order of the argument and the exercises.

Why generics

There are two reasons for generics, and they have nothing to do with each other. Keep them apart:

  1. Type safety — without a declared element type, a collection accepts anything and hands everything back as Object, so the caller casts, and a wrong cast is a run-time crash.
  2. Reuse — without a type parameter, a class that works on one type has to be copied once per type.

Everything after that is the same parameter T being progressively constrained: unbounded (<T>) → bounded at the declaration site (<T extends Number>) → bounded at the use site (? extends T, ? super T) → and finally erased entirely, so none of it survives compilation.

Why 01 — the cast you should not have to write

Prior to Java 1.5 collection classes could hold any type of object: ArrayList declared public boolean add(Object o). Every element comes back as Object, so each get needs a cast, and the compiler cannot check that the cast is right.

Figure 41: Type safety with and without generics. Left: a raw List holding a String, an Integer and a Date, with each cell’s type above it and its index below. The three casts that match the element types all succeed. The boxed line, Integer num = (Integer) list.get(2);, compiles, but slot 2 holds a Date, so it throws ClassCastException when the program runs. Right: the same list parameterised by String, where the bad line list.add(123) is refused before the program ever runs and get needs no cast. The red squiggle marks a compile-time error. The magenta lines give the verdict: the raw list’s mistake is caught at run time, the generic list’s at compile time.

Generics provide type safety. Type safety allows us to catch and prevent type-related errors early and thus prevent unintended bugs. A shopping cart is a second example: a raw List cart accepts new Product("Laptop") and then, by accident, "Not a product". The generic version turns that second add into a compile-time error and drops the (Product) cast from the loop.

See java-casting for what the cast itself is doing, and java-exceptions for ClassCastException.

NoteFun fact: a list of Object

List<Object> list = new ArrayList<>(); accepts both "Hello" and 123, and both come back as Object. What that shows is written up in java-generics.

Why 02 — the class you should not have to copy

The second motivation is duplication. A class that prints an Integer has to be written again for Double, Float and String. The four classes differ in one word, and one generic class replaces them.

Figure 42: Reuse: four classes whose bodies are identical apart from one word, and the single generic class Print<T> that replaces them. Apart from the class and field names, the type outlined in red (Integer/Double/Float/String) is the only difference between the four. Each of the four is a public class and also carries a constructor and a one-line print() body (System.out.println(...)); all of that is elided here so the four fit in one row. At the bottom, three instantiations of the generic class with three different element types.

Generics enable reference types — Integer, String, … and user-defined types — to be parameters when defining classes, interfaces and methods. The word reference matters: Print<int> is not legal, only Print<Integer>.

Naming the type parameter

The convention is a single letter. These show up often in the Java libraries:

Letter Stands for
T Type
E Element — used extensively by the Java Collections Framework (java-collections-framework)
K Key
V Value
N Number
S, U, V… 2nd, 3rd, 4th types

Generic methods, and the two exercises

A method can carry its own type parameter, declared between the modifiers and the return type, whether or not its class is generic:

public <T> void genericsMethod(T data) { /* do something with data */ }

public <T> T genericsMethod(T data) {
    // do something with data here
    return data;                       // returning any T-type value
}

Several at once are allowed, and the return type may be a third one:

public <T, S, R> R genericMethod(T value1, S value2) {
    return null;
}

String result = genericMethod(42, 3.14);   // T = Integer, S = Double, R = String

The two exercises take one method — Printer.print — through three signatures. Exercise 02 is an edit to Exercise 01’s answer, so revise them as one sequence.

Figure 43: Exercises 01 and 02 as one progression. The body is the same at every stage; only the signature changes, and with it the set of arguments the method accepts. A red squiggle marks a call the compiler rejects. At the starting point printer.print(124) is rejected, and removing that restriction is what Exercise 01 exists to do. Exercise 02 then bounds the parameter, so the String call on the bottom row is rejected. The teal arrows are the two exercises, each a change of signature.

At the middle stage the Java compiler automatically determines the type of T from the type of the argument passed to the method. This is known as type inference.

Bounded generics

In general, the type parameter can accept any reference data type. Bounded generics are used if we want to use generics for some specific types.

The form is <T extends X>: T can only accept data that are subtypes of X. It is the java-inheritance relation being used as a constraint. The example classes are Person, Student and Professor.

Despite the keyword, extends in a bound also covers implementing an interface. There is no implements form of a bound. This is needed to read library signatures.

Bounds through wildcards

The bound above sits at the declaration site. Wildcards move the same idea to the use site — a parameter list. There are three forms:

Form Name Use
List<?> unbounded wildcard read only; writing is refused outright
? extends T upper bound wildcard mainly to read data from a structure
? super T lower bound wildcard to perform write operations

Choosing between <T> and <?>:

  • Use <T> when you need to work with the type.
  • Use <?> when you only need to read values.
  • Wildcards are usually bounded (<? extends T>, <? super T>) to reduce flexibility and improve safety.

The reason upper bounds are needed at all is invariance (Effective Java, Item 31): parameterized types are invariant, so List<Type1> is neither a subtype nor a supertype of List<Type2>. So sum(List<Number>) rejects a List<Double> even though Number n = 5.0; is fine. Widening the parameter to sum(List<? extends Number>) fixes it.

java-generics carries the code for all three forms, the addSomething / sum / addNumbers examples, and a figure of the Number tree showing which lists each wildcard admits.

Type erasure

All of the above is compile time only. Java implements generics by erasing every type parameter during compilation — replacing it with its upper bound, or with Object if unbounded — so generic type information is not available at run time. The compiler then inserts the casts the erased code needs. The (String) cast that generics took out of the source is still there in the compiled code; you just did not type it.

The two erasure examples and the compile-time/run-time pair are drawn out in java-generics.

Practical example: the bookshop

A worked design problem: a bookshop selling Fiction, Action and Fantasy books held in bookshelves. There are three designs: one BookShelf of Book (reusable, needs casts, and one line throws), a separate shelf class per genre (type safe, duplicated), and finally BookShelf<T extends Book> (both). The listings and a figure comparing the three designs are in java-generics.

The bound is needed in that last version: displayBooks() calls book.getGenre(), which is only legal because the compiler knows every T is at least a Book. An unbounded BookShelf<T> would not compile.

Homework

  • What if we use a generic class instead? Rewrite the Printer exercise with the type parameter on the class rather than the method, then work out why printer.print(123) is now an error on a Printer<String>. The reasoning is written up in java-generics.

Further reading

The course’s CodeCamp playlist has supplementary material, and the course Git repo has the code samples.

Generics come back in the Week 12 practical, week12-lab-generics.

Applied class

See week9-tutorial-substitution-principle-and-pre-post-conditions — more practice with the Liskov Substitution Principle (from java-solid-principles, Week 7) and pre/postconditions (from java-specification, Week 3). It runs in three parts: ranking six pairs of predicates by strength; deciding, for each of those pairs, whether putting them in as preconditions or as postconditions keeps substitutability; and then writing Javadoc for a small q2 method — @param/@return first, then @requires/@ensures, then a frame condition saying the method changes nothing in the array.

The worked X/Y/Z example is the one to remember: Y widens the precondition and narrows the postcondition, so it is legal; Z narrows the postcondition correctly but also narrows the precondition (> 5 instead of >= 5, forbidding 5), and that is the violation.

Practical

See week9-lab-refactoring — refactoring in the small and in the large, extending java-refactoring (Week 6). The “in the small” half is a Connect 4 class taken through style fixes, better names, while→for, magic numbers to constants, decomposition into helper methods, comments, and finally removing the duplicated win-checking code into checkWin / checkHorizontalWin / checkVerticalWin. The “in the large” half breaks a monolithic Library class into Book, BookShelf, Borrower and BorrowingSystem — see java-cohesion-and-coupling.

That practical solution lands on Book and BookShelf — the same two classes the bookshop generics example is built from, arrived at from cohesion rather than from type safety.

Refactoring

Practical for 2026-04-30-generics-in-java (Week 9). Extends java-refactoring (Week 6) with a full worked refactoring of a Connect 4 implementation, plus a “refactoring in the large” exercise using java-cohesion-and-coupling and java-solid-principles (SRP, DIP).

Setup

The provided .zip contains:

resources/oTowerWin.txt
resources/simpleWin.txt
resources/towerWin.txt
src/library/Library.java
src/Connect4.java
test/Connect4Test.java

Connect4 has one method, play, implementing (most of) the gameplay; the three resources/*.txt files are recorded games the tests replay. Library is a separate library-management system, used for the second half. Set up version control before refactoring (see java-version-control), so each refactoring step is a separate commit that can be reverted if it breaks something.

The running program prints the seven column headings 0123456, then the board, then prompts the current player (Player O: 6, Player X: 0, …) for the column to drop into, and finally prints Player X wins. That console transcript is the external behaviour the refactoring must not change.

Refactoring in the small

Goal: make an existing, working class more readable and understandable without changing its behaviour — the unit tests must keep passing after every change. “In the small” refactorings touch one method/class’s internals, not the overall class structure.

Checklist:

  1. Code adheres to the course style guide.
  2. Complex operations are explained.
  3. Logical blocks of code are grouped with whitespace.
  4. Methods have been decomposed such that each method has one clear purpose.
  5. Appropriate data structures are used.

Each item below demonstrates one type of refactoring; none is fully refactored or perfectly styled, and the list is a sample rather than an exhaustive treatment.

Style guide fixes (vertical and horizontal whitespace) — trivial with a linter like Checkstyle:

// Before
int x=0;
while (x < 7){out.print(x); x++;}

// After
int x = 0;
while (x < 7) {
    out.print(x);
    x++;
}

Bad naming — replace cryptic names with meaningful descriptions:

// Before
public static void play(Scanner i, PrintWriter out) {
    int[] n = new int[7 * 6];
    int[] m = new int[7 * 6];
    boolean t = false;
}

// After
public static void play(Scanner in, PrintWriter out) {
    int[] boardX = new int[7 * 6];
    int[] boardO = new int[7 * 6];
    boolean isTurnX = false;
}

while loops that execute a fixed number of times — replace with for:

// Before
int x = 0;
while (x < 7) { out.print(x); x++; }
x = 0;
while (x < 42) { ... x++; }

// After
for (int x = 0; x < 7; x++) { out.print(x); }
for (int x = 0; x < 42; x++) { ... }

Magic numbers — replace with named constants:

private static final int ROW_SIZE = 7;
private static final int COL_SIZE = 6;

for (int i = 0; i < ROW_SIZE; i++) { out.print(i); }
for (int i = 0; i < ROW_SIZE * COL_SIZE; i++) { ... }

Decomposition — even code that isn’t duplicated can be pulled into a helper method if it has a single, nameable purpose (here, printing the board):

private static void printBoard(int[] boardX, int[] boardO,
                               PrintWriter out) {
    for (int i = 0; i < ROW_SIZE; i++) { out.print(i); }
    for (int i = 0; i < ROW_SIZE * COL_SIZE; i++) { ... }
}

public static void play(Scanner in, PrintWriter out) {
    ...
    printBoard(boardX, boardO, out);
    ...
}

Comments — explain complex lines or the purpose of a block, not what is already obvious from the code:

for (int s = 0; s < 42; s++) {
    boolean nf = true;
    boolean mf = true;
    // Check horizontal win
    for (int q = 0; q < 4; q++) {
        if ((s + q) / 7 != s / 7) {
            // Found row out of bounds, not a win
            nf = false;
            break;
        }
        if (boardX[s + q] == 0) {
            // Found position that isn't an X, not a win
            nf = false;
        }
    }
    ...
}

Duplication — repeated blocks that do the same thing become helper methods whose differences are the parameters. The original win check repeats a near-identical horizontal/vertical scan for both players, and is refactored in two stages.

Stage 1 — extract a checkWin(int[] playerBoard) helper parameterised on which player’s board to check, removing the per-player duplication:

private static boolean checkWin(int[] playerBoard) {
    boolean win = true;
    // horizontal win
    for (int q = 0; q < 4; q++) {
        if ((s + q) / 7 != s / 7) { return false; }     // out of bounds
        if (playerBoard[s + q] == 0) { win = false; }   // not the player's piece
    }
    if (win) { return true; }

    win = true;
    // vertical win
    for (int q = 0; q < 4; q++) {
        if (s + (q * 7) >= 42) { return false; }
        if (playerBoard[s + (q * 7)] == 0) { win = false; }
    }
    return win;
}

// in play():
for (int s = 0; s < 42; s++) {          // check win
    if (checkWin(boardX)) { out.println("Player X wins"); exit = true; }
    if (checkWin(boardO)) { out.println("Player O wins"); exit = true; }
}

Stage 2 — split checkWin again into checkHorizontalWin/checkVerticalWin, each returning as soon as a check fails. This is mostly about comprehension, but it also removes the need to store a win variable at all:

private static boolean checkHorizontalWin(int[] playerBoard) {
    for (int q = 0; q < 4; q++) {
        if ((s + q) / 7 != s / 7) { return false; }
        if (playerBoard[s + q] == 0) { return false; }
    }
    return true;
}

private static boolean checkVerticalWin(int[] playerBoard) {
    for (int q = 0; q < 4; q++) {
        if (s + (q * 7) >= 42) { return false; }
        if (playerBoard[s + (q * 7)] == 0) { return false; }
    }
    return true;
}

private static boolean checkWin(int[] playerBoard) {
    return checkHorizontalWin(playerBoard) || checkVerticalWin(playerBoard);
}

Data structures — the flat 42-slot array representing the board is clumsy. Three things to try (partly a matter of personal preference):

  1. Change the flat array of 42 slots to a nested array of 6 rows with 7 slots (int[] boardX = new int[7 * 6]; becomes int[][] boardX = new int[7][6];). This breaks every existing use of the board, so a lot of the class has to be (gradually) rewritten.
  2. Combine the two per-player arrays into one board — 1 at a position means X, 2 means O. This avoids the two data structures accidentally getting out of sync.
  3. Turn the array into a boolean[]. Since boardX and boardO only ever store 1 or 0, they are effectively boolean arrays already.

Why the win check indexes the way it does

The two guards in checkWin are the least obvious lines in the class, and they are exactly what the “comments” refactoring above was for: both exist because the board is flat, so a run of four can silently walk off the edge of one row and onto the next, or off the end of the array.

Figure 44: The two bounds checks in the win scan, drawn on the flat board. With 7 slots per row, a horizontal run is s, s+1, s+2, s+3 and stays on one row only while (s+q)/7 == s/7 — the left grid shows a run that satisfies it and one that wraps onto the next row. A vertical run is s, s+7, s+14, s+21, which needs no row test but must stay inside the array, hence s + q*7 >= 42 — the right grid shows the run that falls off the end. The four example values of s exercise each branch.

This is also the clearest argument for the “data structures” refactoring: with int[][] boardX = new int[7][6], the horizontal guard becomes a plain column-index bound and the /7 arithmetic disappears — which is why it is worth the rewrite it forces.

Refactoring in the large

Goal: given a reasonably well-styled class that has low cohesion and too many responsibilities, split it into smaller, more cohesive classes with clear responsibilities — to make the code reusable and extensible, not just readable. Starting point: a library management system implemented entirely in the Library class.

Considerations when doing this:

  • Each class serves one single-minded purpose (high cohesion).
  • Each class has only one reasonable reason to change (SRP, see java-solid-principles) — e.g. a change of classification system, a change of bookshelf rendering, or a change of customer management process should each land on one class.
  • The interface of each class is designed to have reasonable programmatic interaction.
  • Each component depends on abstractions such that each sub-component can be substituted or extended later (DIP, see java-solid-principles).

For this exercise, don’t worry about “over-engineering” — make the refactored system as flexible as possible.

A possible split of Library (these are the basic classes — a real system could expand on this considerably):

  • Book — keeps track of data related to a single book (eg. title, author, id).
  • BookShelf — keeps track of all the Books in the library and their availability status.
  • Borrower — keeps track of data related to a borrower (eg. name, id) and the books they’re currently borrowing.
  • BorrowingSystem — handles borrowing and returning; the “bridge” that passes data between BookShelf and Borrower.

Figure 45: The Library monolith and the four-class split, with the dependencies that make BorrowingSystem a bridge: it is the only class that knows about both BookShelf and Borrower, so neither of those has to know about the other. A solid line with a solid arrowhead means Uses and points from depender to dependee; the block arrow means ‘becomes’. All four classes are concrete and no interface is drawn, although the DIP consideration asks for dependencies on abstractions.

Substitution Principle and Pre/Post Conditions

Applied class for 2026-04-30-generics-in-java (Week 9). More practice applying the Liskov Substitution Principle (see java-solid-principles) and pre/postconditions (see java-specification).

Everything here turns on one idea: a condition is stronger when it is more restrictive — when satisfying it implies satisfying the other, but not the reverse. Every task below is an application of that, first to bare predicates, then to a subclass’s contract.

Predicate strength

A B
1 a < 0 && b < 0 a != 0 && b < 0
2 a instanceof Animal a instanceof String
3 a instanceof Animal \|\| b instanceof Zebra a instanceof Animal && b instanceof Zebra
4 a instanceof Animal && b instanceof Zebra a instanceof Animal
5 a instanceof Animal && b instanceof Object a instanceof Animal
6 a instanceof Zebra a instanceof Tiger

For each row, identify which column is a stronger (more restrictive) condition, or state that there’s no relation.

  1. A is stronger than B — a < 0 && b < 0 implies a != 0 && b < 0 (every a < 0 is also a != 0), but not vice versa.
  2. No relation — Animal and String are unrelated types; neither instance check implies the other.
  3. B is stronger than A — A only needs either condition to hold (a looser OR), while B requires both (a stricter AND) — satisfying B always satisfies A, not the reverse.
  4. A is stronger than B — A requires everything B requires, plus more (b instanceof Zebra on top of a instanceof Animal).
  5. A looks stronger than B, but they’re equivalent — since everything is an instance of Object, b instanceof Object is always true, so it adds no actual restriction.
  6. No relation — Zebra and Tiger are siblings (both presumably subtypes of Animal, say), so neither instance check implies the other.

Now consider two possible class structures:

// Option 1: Preconditions
class ClassA {
    /** @requires A */
    void f(Object a, Object b) {}
}
class ClassB extends ClassA {
    /** @requires B */
    void f(Object a, Object b) {}
}
// Option 2: Postconditions
class ClassA {
    /** @ensures A */
    void f(Object a, Object b) {}
}
class ClassB extends ClassA {
    /** @ensures B */
    void f(Object a, Object b) {}
}

For each row above, if column A and column B are inserted as the specification text, which option (if any) satisfies the substitution principle?

Recall: a subclass must not strengthen preconditions (they may only stay the same or weaken) and must not weaken postconditions (they may only stay the same or strengthen).

  1. Option 1 (precondition) — ClassB’s precondition (B) is weaker than ClassA’s (A), which is allowed for preconditions.
  2. Neither — unrelated conditions satisfy neither the “no stronger precondition” nor “no weaker postcondition” rule.
  3. Option 2 (postcondition) — ClassB’s postcondition (B) is stronger than ClassA’s (A), which is allowed for postconditions.
  4. Option 1 (precondition) — same reasoning as row 1: B is weaker than A.
  5. Both — since A and B are equivalent here, substituting either as precondition or postcondition preserves the (unchanged) strength relationship.
  6. Neither — unrelated conditions again satisfy neither rule.

Rows 1, 3 and 4 each land in exactly one column: a strength relation that is legal for a precondition is illegal for a postcondition and vice versa, which is why “B is weaker” is never on its own an answer — you have to know which end of the contract it sits at.

Substitution principle

class X {
    /**
     * @require fontSize >= 5
     * @ensure \result >= 0
     */
    int detexify(Object symbol, float fontSize) {
        // Things happen here
    }
}

class Y extends X {
    /**
     * @require fontSize > 0
     * @ensure \result > 0
     */
    int detexify(Object symbol, float fontSize) {
        // Other things happen here
    }
}

class Z extends X {
    /**
     * @require fontSize > 5
     * @ensure \result > 0
     */
    int detexify(Object symbol, float fontSize) {
        // Do other things happen here?
    }
}

The tags are spelled @require/@ensure here but @requires/@ensures in the sections either side. Both spellings appear across the course — see csse2002-diagram-notation, Inconsistencies 5 — so neither is safe to treat as the house form.

Figure 46: X, Y and Z drawn as the pre/postcondition funnels from 2026-04-16-solid-principles-ii. The mouth above each box is the set of inputs the method accepts, the mouth below is the set of outcomes it may produce, and a wider mouth is a weaker condition — so a legal override needs a top mouth at least as wide as its parent’s and a bottom mouth no wider. X’s two mouths are ghosted over Y and Z for comparison. Read off: Y widens the top and narrows the bottom, both legal; Z narrows the top, which is what breaks it. The verdicts are in magenta, with a pointer to the input Z refuses.

Why would a programmer choose to use a precondition at all?

As a restriction on the allowable range of inputs, to avoid having to handle huge positive/negative numbers (or other awkward edge cases) inside the method body.

Does Y violate the substitution principle?

No. Y’s precondition (fontSize > 0) is weaker than X’s (fontSize >= 5 implies fontSize > 0, but not vice versa — the range of acceptable inputs expanded), and Y’s postcondition (\result > 0) is stronger than X’s (\result >= 0 — the range of possible outputs contracted). Both changes are allowed by the principle.

Does Z violate the substitution principle?

Yes. Z’s postcondition is correctly more restrictive of possible outputs (\result > 0 vs. \result >= 0). However, the precondition is also more restrictive (fontSize > 5 vs. fontSize >= 5) — it forbids 5 as a possible input, which X explicitly allowed. Strengthening a precondition violates the principle, regardless of what happens to the postcondition.

Writing pre/postconditions

public boolean q2(String[] strArray, int firstIndex, int secondIndex) {
    return strArray[firstIndex] == strArray[secondIndex];
}

Write a Javadoc comment for q2.

/**
 * Determines if two indicated elements of an array of Strings
 * refer to the same String object.
 *
 * @param strArray an array of Strings
 * @param firstIndex index of the first element to compare
 * @param secondIndex index of the second element to compare
 * @return true if the indicated elements in the array refer to
 *         the same string, false otherwise
 */
public boolean q2(String[] strArray, int firstIndex, int secondIndex) {
    return strArray[firstIndex] == strArray[secondIndex];
}

The description says refer to the same String object rather than “are equal”: the method uses == on references, not .equals.

Add @requires/@ensures tags for all appropriate pre- and postconditions.

/**
 * ...
 * @requires strArray != null && 0 <= firstIndex < strArray.length
 *               && 0 <= secondIndex < strArray.length
 * @ensures \result == true
 *              <==> strArray[firstIndex] == strArray[secondIndex]
 */

The precondition is everything the body needs in order not to throw: a non-null array and two in-range indices. The postcondition is written as an <==> (if and only if), not just “returns true when …”, so it also pins down when the result is false.

Specify that q2 does not change any elements of strArray.

/**
 * ...
 * @ensures \forall int i; 0 <= i && i < strArray.length
 *              ==> \old(strArray)[i] == strArray[i]
 */

\old(...) is the value on entry to the method, so this says every slot holds the same reference afterwards as it did before.

Week 10

Java I/O

Practical for Week 10 (no lecture this week). Extends java-io (Week 8) with saving/loading a data model to/from files, plus a file-format design exercise.

Setup

Provided classes: Schedule, Airport, Flight, DayOfWeek, BadScheduleException (an airline schedule of flights between airports), plus an unrelated Maze class.

Airline schedule

Goal: make a Schedule’s data persistent by saving/loading it to/from a file.

Task 0 — implement Schedule.toString() per its Javadoc spec.

@Override
public String toString() {
    StringJoiner joiner = new StringJoiner(System.lineSeparator());
    joiner.add(String.valueOf(getConnectedAirports().size()));
    joiner.add(String.valueOf(this.flights.size()));
    for (Airport airport : getConnectedAirports()) {
        joiner.add(airport.toString());
    }
    for (Flight flight : this.flights) {
        joiner.add(flight.toString());
    }
    return joiner.toString();
}

Task 1 — implement void save(String filename), propagating any exceptions rather than handling them:

public void save(String filename) throws IOException {
    BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
    writer.write(this.toString());
    writer.close();
}

Between them, toString() and load() fix a file format. toString() emits two counts and then the airports and flights in that order; load() has to consume exactly the same thing, which is what makes the two counts load-bearing — they are what tells the reader how many times to go round each loop:

Figure 47: The Schedule file format fixed by toString() and load(). The two counts shown (2 airports, 3 flights) are an illustrative instance, not a fixture of the format. The teal arrows record the dependency that makes the format parseable at all: each header count governs the trip count of one read loop. The four flight fields are pinned exactly by load() - lineParts[0] goes to Integer.parseInt, [1] and [2] are matched against Airport.getCode(), [3] to DayOfWeek.valueOf - whereas the two airport fields are only ever passed straight to new Airport(lineParts[0], lineParts[1]), so which of them is the code is not settled by load() and they are left unnamed.

Every BadScheduleException thrown by load() below is one of the ways the file on disk can fail to match Figure 47: a header line missing, a count that isn’t a number, a data line missing, a line with the wrong number of |-separated fields, or an airport code a flight refers to that never appeared in the airport block.

Task 2 — implement static Schedule load(String filename), using two private helpers (readFlight, readAirport) and throwing BadScheduleException on a failed numeric parse or an unknown airport code:

public static Schedule load(String filename) throws IOException, BadScheduleException {
    BufferedReader reader = new BufferedReader(new FileReader(filename));

    String airportsLine = reader.readLine();
    String flightsLine = reader.readLine();
    if (airportsLine == null || flightsLine == null) {
        throw new BadScheduleException();
    }

    int numAirports, numFlights;
    try {
        numAirports = Integer.parseInt(airportsLine);
        numFlights = Integer.parseInt(flightsLine);
    } catch (NumberFormatException e) {
        throw new BadScheduleException();
    }

    List<Airport> airports = new ArrayList<>();
    for (int i = 0; i < numAirports; ++i) {
        airports.add(readAirport(reader));
    }
    List<Flight> flights = new ArrayList<>();
    for (int i = 0; i < numFlights; ++i) {
        flights.add(readFlight(reader, airports));
    }

    return new Schedule(flights);
}

private static Flight readFlight(BufferedReader reader, List<Airport> airports)
        throws IOException, BadScheduleException {
    String line = reader.readLine();
    if (line == null) {
        throw new BadScheduleException();
    }

    String[] lineParts = line.split("\\|");
    if (lineParts.length != 4) {
        throw new BadScheduleException();
    }

    int flightNumber;
    try {
        flightNumber = Integer.parseInt(lineParts[0]);
    } catch (NumberFormatException e) {
        throw new BadScheduleException();
    }

    Airport origin = null, destination = null;
    for (Airport airport : airports) {
        if (airport.getCode().equals(lineParts[1])) {
            origin = airport;
        }
        if (airport.getCode().equals(lineParts[2])) {
            destination = airport;
        }
    }
    if (origin == null || destination == null) {
        throw new BadScheduleException();
    }

    DayOfWeek dayOperating = DayOfWeek.valueOf(lineParts[3]);
    return new Flight(flightNumber, origin, destination, dayOperating);
}

private static Airport readAirport(BufferedReader reader) throws IOException, BadScheduleException {
    String line = reader.readLine();
    if (line == null) {
        throw new BadScheduleException();
    }

    String[] lineParts = line.split("\\|");
    if (lineParts.length != 2) {
        throw new BadScheduleException();
    }

    return new Airport(lineParts[0], lineParts[1]);
}

readAirport has to declare BadScheduleException as well as IOException, because its body throws it; with throws IOException alone the listing does not compile.

readFlight/readAirport both throw BadScheduleException for a malformed line — this is a form of defensive programming (see java-specification) protecting the Schedule created by load() from corrupt input, rather than letting a NullPointerException/ArrayIndexOutOfBoundsException leak out from deeper in the parsing logic.

Maze — designing a file format

Maze maps (row, column) positions to tile types (start, end, wall, empty). Unlike Schedule, there’s no existing format to follow — the task is to design one that’s sufficient to save and reload a Maze’s full state.

Task 3 — design a file format for Maze. (Hint: the class’s invariants may let you store less than a full grid dump.)

Several reasonable designs, each with different tradeoffs:

  1. Visual dump — store the same characters render() would print (e.g. # for wall, S/E for start/end). Human-readable, but more complex to parse back than necessary.
  2. Linear encoding of every tile — e.g. #S#E for a 2×2 grid means wall at (0,0), start at (0,1), wall at (1,0), end at (1,1) (with or without an outer border wall included).
  3. One line per map entry — e.g. 1,2,# means “wall at (1, 2)”. Simple, but verbose for large mazes with many walls.
  4. Only relevant tiles — the first two stored positions are always start/end, and every position after that is implicitly a wall; positions can be (row, column) pairs or a single linear index (rows * row + column).
  5. Start/end positions + a bitmap — store start and end explicitly, then a bit per remaining tile (1 = wall, 0 = empty).
  6. Start/end positions + wall runs — store start and end, then walls as (start, end) position pairs, so a run of adjacent wall tiles can be stored as a single entry instead of one entry per tile.

Options 4-6 are the ones the hint is pointing at: each leans on a regularity in the data rather than dumping the grid verbatim — 4 and 6 store only the tiles that are not empty (6 collapsing adjacent walls into runs), and 5 still visits every remaining tile but spends one bit on it instead of a whole character.

Coupling and Cohesion

Applied class for Week 10 (no lecture this week). More practice applying java-cohesion-and-coupling (Week 6).

Coupling

Class coupling: the strength of the connection or dependence between classes — to what extent does this class depend on other classes? How many methods are called on how many other classes? Can another object influence the flow of control in this object?

Assume the following classes are all in separate files in the same package:

public class X {
    public int num = 5;
    protected Z z;

    public X(Z z) { this.z = z; }

    public void doThis() { sayHello(); }

    public void sayHello() { System.out.println("Hello"); }
}
public class Y extends X {
    public Y(Z z) { super(z); }

    public void doThat() { this.z.sayHello(); }

    @Override
    public void sayHello() { super.sayHello(); }
}
public class Z {
    private X x = new X();

    public void setNum(int num) { x.num = num; }

    public void sayHello() { System.out.println("Hello"); }
}

These classes are tightly coupled, to a degree that is possibly unrealistic — every pair of them is connected. Identify the points of coupling between: (0) X and Y; (1) X and Z; (2) Y and Z — you don’t need to name the type/level of coupling (see java-cohesion-and-coupling for the ladder from content coupling down to none), just where it occurs.

As written, Z’s private X x = new X() would not compile, because X declares only X(Z z) and so has no no-argument constructor. The exercise is about locating coupling, not about compiling the listing.

Class Coupling Implication
X stores a Z object X is coupled to Z
X constructor takes a Z X is coupled to Z
X doThis() just calls sayHello(), which is overridden in Y forwarding behaviour
Y constructor takes a Z Y is coupled to Z
Y constructor calls super(z) Y is coupled to X
Y doThat() accesses the protected this.z Y is coupled to Z and X
Y sayHello() calls X.sayHello() via super Y is coupled to X
Z stores an X object Z is coupled to X
Z setNum() accesses the public X.num Z is coupled to X

Drawn as a dependency graph, the table says that every pair of these three classes is joined, and that X and Z are joined in both directions — a dependency cycle, so neither can be understood, tested or reused without the other:

Figure 48: The coupling points of Task 0-2 collected into a dependency graph. The table’s nine rows become four edges: X and Z point at each other, Y points at Z, and one extends edge carries every X-Y row at once (super(z), super.sayHello(), and doThis() forwarding to a sayHello() that Y overrides). A solid teal arrow means ‘uses’ and points from the depender to the thing it depends on. The black line with an unfilled triangle head is the generalisation arrow, with the superclass above. Members carry the visibility prefixes - (private) and + (public), and X’s protected field is spelled out in words.

Two points the table makes that Figure 48 makes visible at once:

  • The X–Z pair is a cycle. X holds a Z and takes one in its constructor; Z holds an X and writes straight into its public num field.
  • Y’s single line this.z.sayHello() reaches a Z through a field it did not declare, so it couples Y to Z and to X at the same time — which is why the table gives that one row two implications.

Cohesion — Customer

Class cohesion: how well components support a central purpose — how focused the components of a unit are. How well do the parts of the class (state and methods) fit together? Do they all contribute to a single, clear purpose?

public class Customer {
    private String name;
    private String streetAddress;
    private String suburb;
    private String postCode;
    private List<Item> orders; // the products that have been ordered

    public Customer(String name, String streetAddress, String suburb, String postCode) {
        this.name = name;
        this.streetAddress = streetAddress;
        this.suburb = suburb;
        this.postCode = postCode;
        this.orders = new ArrayList<>();
    }

    public String getName() { return name; }
    public String getMailingAddress() { return streetAddress + suburb + postCode; }
    public void newOrder(List<Item> order) { orders.addAll(order); }
    public List<Item> getAllOrder() { return orders; }
}

Does Customer exhibit high or low cohesion? Justify your answer.

Low cohesion:

  • name is only used once, in a single getter.
  • streetAddress/suburb/postCode are only used once, in a single getter — and these aren’t unique to a Customer, so belong in a separate class.
  • orders (with its getter and add method) isn’t cohesive with the rest of Customer’s representation, and could live in a dedicated Order-related class.

The grouping of member variables looks coincidental, and the methods have no clear relationship to each other’s functionality — the state and methods don’t contribute to a single, clear purpose.

If Customer doesn’t have high cohesion, design replacement classes with higher cohesion.

Customer is really trying to be at least three concepts at once: a customer, a mailing address, and a customer’s order history. Extract a postal-address abstraction (that Customer stores an instance of), and an order-history abstraction (stored by Customer, or managed separately).

Figure 49: Customer as written, and split into its three concepts: a customer, a mailing address (PostalAddress) and a customer’s order history (OrderHistory). The solid teal arrow means ‘uses’ and should not be read as UML aggregation or composition. The magenta note says that the order history may equally be managed outside Customer. The weaker design is on the left and the stronger on the right, each labelled with one word beneath.

The point of Figure 49 is that nothing is deleted and no behaviour changes — the same five fields and four methods are still there. All that moves is which class owns them, and with it the number of reasons any one class has to change.

Cohesion — Employee

public class Employee {
    private String firstName;
    private String surname;
    private String homeAddress;
    private String suburb;
    private String postCode;
    private String currentRole;
    private int currentRoleSecurityLevel;
    private int hourlyWage;

    public Employee(String fName, String lName, String homeAddress,
                     String suburb, String postCode, int hourlyWage) {
        this.firstName = fName;
        this.surname = lName;
        this.homeAddress = homeAddress;
        this.suburb = suburb;
        this.postCode = postCode;
        this.hourlyWage = hourlyWage;
    }

    public String getName() { return surname + ", " + firstName; }
    public String getMailingAddress() {
        return String.format("%s%n%s%n%s", homeAddress, suburb, postCode);
    }
    public void setRole(String newRole, int securityLevel) {
        currentRole = newRole;
        currentRoleSecurityLevel = securityLevel;
    }
    public String getCurrentRole() { return currentRole; }
    public boolean accessAllowed(int requiredSecurityLevel) {
        return currentRoleSecurityLevel >= requiredSecurityLevel;
    }
    public int getPay(int hoursWorked) { return hourlyWage * hoursWorked; }
    public void setHourlyWage(int newWage) { hourlyWage = newWage; }
}

Does Employee exhibit high or low cohesion? Justify your answer.

Low cohesion:

  • firstName/surname are only set in the constructor and returned by a single getter — better as a dedicated personal-details class, or simply a single name string.
  • The address fields are assigned once and used in a single getter — they appear arbitrarily grouped in this class and could live in a separate object.
  • The role fields (currentRole, currentRoleSecurityLevel) are used across several methods, but never interact with the name or address fields — this functionality could move to a Role class, shrinking Employee’s constructor and letting other objects reuse Role.

Employee is really trying to wrap the functionality of at least two other objects (address, role) inside itself; since the grouping of state appears coincidental rather than purposeful, Employee has low cohesion.

“The grouping appears coincidental” is a claim you can check mechanically: tabulate which method reads or writes which field, and see whether the marks form one connected mass or several disjoint blocks.

Figure 50: Which Employee method touches which Employee field. The constructor is deliberately left out: it assigns every field by definition, so it says nothing about cohesion. The result is four disjoint blocks with no mark outside them: no method in this class touches fields from two different blocks, which is exactly what ‘the grouping of state appears coincidental’ means, and exactly why each block can be lifted out into a class of its own. Block outline colours carry group identity only.

Compare the same test applied to a cohesive class: there the marks would spread across the whole grid, because the methods would share the state they operate on. Here they do not overlap at all — Figure 50 is four small classes drawn inside one large one.

Week 11

Lambdas, Streams and Events

See csse2002 for course logistics.

Lambdas are examinable; event-driven programming and GUIs are not — confirmed in 2026-05-28-course-summary-and-exam-preparation. The two halves carry very different revision weight.

Topics

  1. Lambdas in Java — anonymous functions, scope, and the functional interfaces that give them a type. Examples: an anonymous function in JS, in Python and in Java; what a lambda captures from its enclosing scope; filtering with a Predicate.
  2. Streams in Java — a basic .stream() example, then one worked pipeline, built up one line at a time.
  3. Events — including how to make your own toy event system.
  4. An anecdotal survey of QLD dev teams (see below).

All the technical content lives in java-lambdas-and-streams and java-events.

Events

Using an event API is easy to pick up. It is often the first design pattern people use at high school, wiring up buttons on a website, without realising it. Two things are not picked up naturally:

  1. a basic, naive event system implementation, which shows what is going on under the hood;
  2. a variant of the CSSE2002 game engine (the engine used in the assignments) with an event system integrated, which shows how much “connective tissue” code it removes.

Both are written up in java-events.

Applied class

See week11-tutorial-dependency-inversion — more practice with Dependency Inversion, extending java-solid-principles (Week 7).

Aside: anecdotal local industry survey

An informal, anonymised survey of one engineer’s professional network: 14 QLD-based dev teams (13 excluding the surveyor’s own) across 12 distinct organisations. It is not representative data. It reflects only one person’s connections in the dev scene, with no QLD teams in big tech, consultancies or banks. The findings (on AI tool usage and graduate hiring) are not course content.

Dependency Inversion

Applied class for 2026-05-14-lambdas-streams-and-events (Week 11). More practice applying Dependency Inversion and Dependency Injection (see java-solid-principles, where the principle itself is stated).

(The handout is headed Week 10. It is the week 11 applied class.)

Dependencies

A class A has a dependency on class B if A refers to B in code — an import B;, or (if in the same package) simply referring to B anywhere in the code.

import furniture.Lamp;

class Desk {
    HardwoodFloor placedOn;
    List<Junk> items = new ArrayList<>();
    LogitechKeyboard keyboard = new LogitechKeyboard();

    public Desk() {
        placedOn = new HardwoodFloor();
        items.add(new Book("Pragmatic Programmer"));
        items.add(new Monitor());
    }

    public void rotate(Angle angle) {
        if (angle == Angle.LEFT) {
            placedOn.scratch("clockwise");
        }
        // implementation
    }

    public boolean clean() {
        // implementation
    }
}

List the classes Desk depends upon.

Lamp, HardwoodFloor, Junk, List, ArrayList, Book, Monitor, Angle, LogitechKeyboard.

Not all dependencies are equally bad. Two properties determine how good/bad a dependency is:

  • Stability — how likely the dependency is to change. ArrayList is a good dependency because it’s very unlikely to change; in general, treat classes you write as unstable until proven otherwise. Interfaces are usually assumed more stable than concrete classes (unless they’re poorly designed and change often).
  • Exposure — how much of the class uses the dependency. Book (used only in the constructor) is a better dependency than HardwoodFloor (used in any method) simply because less of the class is entangled with it.

Roughly order Desk’s dependencies from best to worst.

  1. List
  2. ArrayList
  3. Lamp (assuming that it isn’t used anywhere)
  4. Book
  5. Monitor
  6. Angle
  7. LogitechKeyboard
  8. HardwoodFloor
  9. Lamp (assuming that it can be used anywhere)

One caveat: since Angle appears to be an enum type, we may reasonably assume it is stable and may consider it a better dependency.

Lamp appears twice because it is ranked under both assumptions: the import is there but no use of Lamp is visible in the listing, so its exposure is either nil (best) or unbounded (worst). The caveat makes Angle a better dependency, which would move it up from sixth.

Dependency Inversion

Dependency inversion is a tool for building software that is more flexible and amenable to future changes.

Dependency Inversion Principle (DIP): depend on abstractions, not concretions (implementations).

To apply it to Desk you first need to know which of its dependencies already have an abstraction behind them. In the diagram, a dashed box indicates an interface.

Figure 51: The structure behind Desk’s dependencies. It carries eight of the nine dependencies listed above - Lamp is absent - plus the new Floor interface. A dashed box indicates an interface. A dashed line with a solid filled arrowhead runs from a concrete class up to the interface it implements.

Read off the diagram: HardwoodFloor, Book, Monitor and ArrayList each already sit under an interface, so the simple form of the DIP applies to them immediately. Angle and LogitechKeyboard sit alone, with no abstraction to switch to. LogitechKeyboard is the one fixed below, with the proper form of the DIP.

Minimising concrete dependencies (the simple form)

The simplest step towards DIP: change a field’s compile-time type from a concrete class to whatever interface it implements (assuming the interface exposes everything the field is used for):

- HardwoodFloor placedOn;
+ Floor placedOn;
public class Warrior {
    private BronzeSword weapon = new BronzeSword();
    private BronzeShield shield = new BronzeShield();

    public void attack(Opponent opponent) { weapon.use(opponent); }
    public void defend(Attack attackType) { shield.block(attackType); }
}

Minimise concrete dependencies for Warrior, based on the class diagram below.

Figure 52: The class diagram for Task 2: dashed box = interface (Weapon), solid box = concrete class, dashed arrow = implements, solid arrow = extends, arrowheads solid-filled and the supertype above. Weapon and BronzeShield are the only two boxes that list a member, on the line below the name. Those two members are the only two methods Warrior actually calls.

BronzeSword has Sword above it and Weapon above that; BronzeShield stands alone, with no interface to retreat to.

- private BronzeSword weapon = new BronzeSword();
+ private Weapon weapon = new BronzeSword();

The solution touches only weapon; shield has to wait for the proper form below.

The proper form of DIP

Minimising concrete dependencies only helps where an abstraction already exists. The proper form of DIP is:

Remove dependencies on low-level components from high-level components — make both depend on an abstraction.

High-level vs low-level isn’t a strict distinction: high-level components implement application logic (e.g. a browser’s back/forward navigation history); low-level components do the grunt work the high-level logic depends on (e.g. actually requesting a webpage’s data). The goal is for high-level components to talk to low-level components exclusively through an abstraction, so a low-level component changing doesn’t force a change to the high-level component depending on it.

Applying this to Desk’s LogitechKeyboard dependency (LogitechKeyboard has no existing interface to fall back on):

  1. Create an abstraction of the low-level component:

    interface Keyboard {
        void type(char key);
        // include other ways to interface with the low-level component
        // multiple interfaces can be used if the low-level component
        // has multiple responsibilities
    }
  2. Modify the low-level component to depend on (implement) the abstraction:

    - class LogitechKeyboard {
    + class LogitechKeyboard implements Keyboard {
  3. Minimise concrete dependencies in the high-level component:

    - LogitechKeyboard keyboard = new LogitechKeyboard();
    + Keyboard keyboard = new LogitechKeyboard();

The name of the principle is in what those three steps do to the arrows:

Figure 53: What is inverted in dependency inversion, for the Desk-to-LogitechKeyboard example. A dashed box is an interface and a dashed arrow with a filled head means implements. A depends-on edge is a solid line with a solid head, pointing from the depender to what it depends upon.

Desk still depends on something, and LogitechKeyboard is still the thing that runs, yet the edge that used to run from the high-level component to the low-level one now runs the other way — from the low-level component up to the shared abstraction. That reversal is the “inversion”.

Apply the proper form of DIP to Warrior’s BronzeShield dependency.

interface Shield {
    void block(Attack attack);
}
- class BronzeShield {
+ class BronzeShield implements Shield {
- private BronzeShield shield = new BronzeShield();
+ private Shield shield = new BronzeShield();

Dependency Injection

Even after minimising concrete dependencies, Desk still depends on the concrete types when constructing them. Dependency Injection (DI) completes DIP: provide concrete instances to a class as parameters, rather than having the class instantiate them itself:

- public Desk() {
-     placedOn = new HardwoodFloor();
+ public Desk(Floor floor) {
+     placedOn = floor;

Desk no longer needs to change to support a different floor type — the caller just passes a different Floor implementation in. A constructor isn’t the only injection point — a setter is appropriate when the dependency is likely to change over the object’s lifetime:

public changeKeyboard(Keyboard keyboard) {
    this.keyboard = keyboard;
}

Modify Warrior so its concrete types are dependency injected.

public class Warrior {
    private Weapon weapon;
    private Shield shield;

    public Warrior(Weapon weapon, Shield shield) {
        this.weapon = weapon;
        this.shield = shield;
    }

    // it's quite likely that a warrior will change their weapon
    public void equip(Weapon weapon) { this.weapon = weapon; }

    // overloading gives us a nice consistent interface for this action
    public void equip(Shield shield) { this.shield = shield; }

    public void attack(Opponent opponent) { weapon.use(opponent); }
    public void defend(Attack attackType) { shield.block(attackType); }
}

weapon and shield are injected via the constructor and can be swapped later through the overloaded equip(...) setters — setter injection layered on top of constructor injection.

Dependency injection frameworks

Something (typically an entry-point method, e.g. main) still has to construct the concrete dependencies before injecting them. DI frameworks let you defer that construction to runtime, specifying which concrete classes to build via the framework’s own configuration rather than in code. Unless a project needs multiple levels of injected dependencies, good design alone can avoid the extra conceptual overhead of adopting a DI framework.

Week 12

Correct Programming

See csse2002 for course logistics.

Not examinable — confirmed in 2026-05-28-course-summary-and-exam-preparation. Worth knowing, but don’t spend revision time here.

Correctness is the prime quality. If a system does not do what it is supposed to do, everything else about it […] matters little.

— Bertrand Meyer, Object-Oriented Software Construction, §1.2 p.4, 1997

Outline

  1. Specification — what does it mean for a program to be correct?
  2. Deriving preconditions — propagating a postcondition backward through code
  3. Loop invariants — reasoning about (and designing) loops
  4. Pragmatic considerations — when is this worth the effort?

All content is in java-hoare-logic and java-loop-invariants.

Applied class

See week12-tutorial-lambdas-and-streams — 22 tasks on lambdas and streams, extending java-lambdas-and-streams (Week 11). Nothing about correctness: §1 is the three \(\lambda\)-function forms, the standard java.util.function interfaces (Function, BiFunction, UnaryOperator, Predicate, Supplier, Consumer, BiConsumer), method references, effectively-final capture and andThen composition; §2 is filter/map/mapToInt/reduce/sum/forEach and converting a loop into a pipeline.

Practical

See week12-lab-generics — 6 tasks on generics, extending java-generics (Week 9), built on a Bus/Passenger class hierarchy supplied as provided.zip. §1 rewrites a non-generic Bus (which stores Object and forces casts) into Bus<T>, then bounds it to T extends Passenger and subclasses it as NoPetsBus<T extends Person>; §2 adds a BusStop class whose methods need ? extends, ? super, and a generic method — the first two also asking for a @require/@ensure Javadoc comment.

Next steps

Where this material goes next. Treat the list as background reading:

  • CSSE3100 — Reasoning About Programs
  • Floyd, 1967 — Assigning Meanings to Programs
  • Hoare, 1969 — introduced the triple \(\{P\}\,S\,\{Q\}\)
  • Dijkstra, 1975 — weakest-precondition reasoning

CSSE3610/7610 is the follow-on course for concurrent and distributed algorithms (see java-loop-invariants).

Generics

Practical for 2026-05-21-correct-programming (Week 12). Extends java-generics (Week 9) with practice designing a generic class, bounding its type parameter, and using wildcards and generic methods.

All of the classes below are supplied in a provided.zip on the course website. Make a new IntelliJ project and drop the contents in.

Setup

Every later question refers back to one class hierarchy. Each child has one solid arrow pointing straight up into its superclass, and a hollow diamond sits on the Bus end of the Bus–Passenger line.

Figure 54: The passenger hierarchy the whole practical is built on. Each child has one solid arrowhead into its superclass, and a hollow aggregation diamond sits on the Bus end of the Bus–Passenger line.

Passenger is the common supertype of everything that can ride; Pet and Person are its two direct subtypes; TransportWorker (with subtypes MaintenanceStaff and BusDriver) and GeneralPublic (with subtype Concession) are both Persons. A Bus holds passengers up to a fixed capacity.

Keep Figure 54 in view — every wildcard bound in §2 is just a region of this tree.

§1 Generic Bus

Task 0. The provided Bus stores instances of Object. That forces callers to cast on the way out — passengerOff() hands back an Object, not a Passenger:

// The starting Bus class, before the rewrite.
public void passengerOn(Object passenger) { ... }
public Object passengerOff() { ... }

Passenger p = (Passenger) bus.passengerOff();   // cast needed at every call site

You could rewrite Bus to store a Passenger[] instead, but then a bus that may only carry the general public would need an entirely new class storing a GeneralPublic[].

Rewrite Bus to be generic, with one type parameter, so both the casting and the duplication go away. (An Unchecked Cast warning during the rewrite is expected and can be safely ignored here.)

public class Bus<T> {
    private T[] passengers;
    private int currentCount;
    private int capacity;

    public Bus(int capacity) {
        // Creation of an array of objects, that is cast to be of type
        // T, is required due to how generics are implemented in Java.
        this.passengers = (T[]) new Object[capacity];
        this.capacity = capacity;
        this.currentCount = 0;
    }

    public void passengerOn(T passenger) {
        if (currentCount < capacity) {
            passengers[currentCount++] = passenger;
        }
    }

    public T passengerOff() {
        T exitingPassenger = null;
        if (currentCount > 0) {
            exitingPassenger = passengers[--currentCount];
        }
        return exitingPassenger;
    }

    public int getCurrentCount() {
        return currentCount;
    }

    public int getCapacity() {
        return capacity;
    }
}

The (T[]) new Object[capacity] line is the awkward part: Java erases type parameters at compile time, so new T[capacity] is not something the runtime can do — you allocate an Object[] and lie to the compiler about its type. That lie is exactly what the Unchecked Cast warning is about.

passengerOn/passengerOff are a stack, not a queue: passengerOff returns passengers[--currentCount], i.e. the passenger who got on most recently, and returns null on an empty bus rather than throwing.

The remaining tasks extend Bus using bounded generic types. As with every prac, test your code as you go.

Task 1. Modify your class so that only instances of Passenger (and its subclasses) are allowed on the bus.

public class Bus<T extends Passenger> {
    ...
    public Bus(int capacity) {
        this.passengers = (T[]) new Passenger[capacity];
        ...
    }
    ...
}

Two things change together. The bound T extends Passenger restricts the type argument to Passenger or a subtype, so Bus<String> no longer compiles. And because T’s erasure is now Passenger rather than Object, the backing array is allocated as new Passenger[capacity].

A bound also means code inside Bus<T> may call any Passenger method directly on a T value.

Now suppose there is a type of bus that does not allow pets on board — only people.

Task 2. Write a new class NoPetsBus which extends the generic Bus class and only allows non-pets on board.

public class NoPetsBus<T extends Person> extends Bus<T> {
    public NoPetsBus(int capacity) {
        super(capacity);
    }
}

The subclass declares a stricter bound than its parent: T extends Person rather than T extends Passenger. Pet is a Passenger but not a Person (see Figure 54), so NoPetsBus<Pet> simply fails to compile — the exclusion is enforced by the type system, with no instanceof check anywhere.

§2 Bus Stop

The remaining questions need generic methods and wildcards (?). Create a new non-generic class called BusStop; each method below goes in it.

Training Bus

Bus stops are the starting points of training routes for new bus drivers. While a driver is being trained, only the trainee driver and other transport workers are allowed on board. The crew training the driver could be any combination of transport workers: only other bus drivers (List<BusDriver>), only maintenance staff (List<MaintenanceStaff>), or a mix (List<TransportWorker>).

Task 3. Write the trainingBus method:

static Bus<TransportWorker> trainingBus(BusDriver trainee, List<...> trainers)

where ... is replaced with something that allows any of the List types mentioned above to be passed in. The method returns a new bus (capacity 10) with the trainee driver and all the trainers on board. Write a Javadoc comment with appropriate @require and @ensure tags.

Hint. If a List<A> is required, a List<B> cannot be passed in, even if B extends A. So List<TransportWorker> alone will not do — you need wildcards.

/**
 * Populate a bus to be used to train a new driver.
 *
 * @param trainee   New driver to be trained.
 * @param trainers  TransportWorkers who will train the new driver.
 * @require trainee != null && trainers.size() < 10
 * @ensure  \result contains trainee and all trainers
 */
public static Bus<TransportWorker> trainingBus(BusDriver trainee,
        List<? extends TransportWorker> trainers) {

    Bus<TransportWorker> bus = new Bus<>(10);
    bus.passengerOn(trainee);
    for (TransportWorker trainer : trainers) {
        bus.passengerOn(trainer);
    }
    return bus;
}

The hint is the whole point: generic types are invariant, so List<BusDriver> is not a subtype of List<TransportWorker>. List<? extends TransportWorker> is the supertype of all of them.

The precondition trainers.size() < 10 is what keeps the postcondition honest — passengerOn silently does nothing once the bus is full, so without a bound on the crew size the bus would not actually contain all the trainers.

Transfer Students

At bus stops, transfers happen between school buses — used exclusively for school children on concession fares, i.e. Bus<Concession> — and ordinary buses. When school children depart their bus they can only get onto buses that allow concession holders on board (not, for example, a bus meant exclusively for transport workers). So they can move either onto another concession-only bus, or onto a bus that allows superclasses of concession holders on board.

Task 4. Write the transferStudents method:

static void transferStudents(Bus<Concession> students, Bus<...> bus)

where ... is replaced with something that ensures concession holders are allowed onto bus. All students on the students bus should be transferred to bus. Write a Javadoc comment with appropriate @require and @ensure tags.

Hint. Valid bus types are Bus<Concession>, Bus<GeneralPublic>, Bus<Person> and Bus<Passenger>. Wildcards will be useful here too.

/**
 * Transfer students to the new bus.
 *
 * @param students Bus only containing Concession fare riders.
 * @param bus      Bus to which students will transfer.
 * @require students != null
 *          && bus.getCapacity() >= students.getCurrentCount()
 * @ensure  students.getCurrentCount() == 0
 *          && bus.getCurrentCount >= \old(students).getCurrentCount()
 *          && bus contains all passengers from \old(students)
 */
public static void transferStudents(Bus<Concession> students,
        Bus<? super Concession> bus) {

    // Ensure loop condition does not change while iterating
    int numStudents = students.getCurrentCount();
    for (int i = 0; i < numStudents; i++) {
        Concession student = students.passengerOff();
        bus.passengerOn(student);
    }
}

Two things worth pulling out:

  • The lower-bounded wildcard. bus is only ever written to, so Bus<? super Concession> is the right bound — it accepts a bus whose type argument is Concession or any supertype of it, which covers the four types the hint lists, all of which can legally accept a Concession via passengerOn. (Bus<Object> satisfies the bound too; the hint stops at Passenger.)
  • The cached loop bound. Writing for (int i = 0; i < students.getCurrentCount(); i++) would be a bug: every passengerOff() decrements the count while i increments, so the two meet in the middle and only half the students get transferred. Reading the count once, before the loop, is what the code comment (“Ensure loop condition does not change while iterating”) is about.

Reading the two wildcard directions off the hierarchy

Tasks 3 and 4 need wildcards in opposite directions. Task 3 accepts List<BusDriver>, List<MaintenanceStaff> and List<TransportWorker>. Task 4 accepts Bus<Concession>, Bus<GeneralPublic>, Bus<Person> and Bus<Passenger>. Laid on the same tree, ? extends reaches down from its bound and ? super reaches up.

Figure 55: The two wildcard bounds this practical needs, mapped onto the hierarchy. Grey fill marks the type arguments accepted by List<? extends TransportWorker> (Task 3); a dashed border marks those accepted by Bus<? super Concession> (Task 4).

Which direction you need falls out of what the method does with the parameter: trainers is only read (upper bound, ? extends), bus is only written (lower bound, ? super).

Transfer Concession

Suppose new subclasses of Concession were added at a later stage — say SchoolStudent and UniStudent.

Task 5. Write the transferAllConcession method:

static ... void transferAllConcession(Bus<...> students, Bus<...> bus)

which does the same thing as transferStudents, except it works for Concession or any potential subclass of it. That is, if SchoolStudent were a subclass of Concession, this should work without error:

Bus<SchoolStudent> students = new Bus<>(30);
Bus<GeneralPublic> bus = new Bus<>(50);
transferAllConcession(students, bus);

Hint. You will need a generic method for this one.

public static <T extends Concession> void transferAllConcession(
        Bus<T> students,
        Bus<? super T> bus) {

    int numStudents = students.getCurrentCount();
    for (int i = 0; i < numStudents; i++) {
        T student = students.passengerOff();
        bus.passengerOn(student);
    }
}

Declaring <T extends Concession> on the method (before the return type) is what makes the two parameters move together: T is inferred per call site from students, and bus’s bound ? super T is then resolved relative to that same T. With Bus<SchoolStudent> and Bus<GeneralPublic>, T infers as SchoolStudent, and GeneralPublic is indeed a supertype of it.

Task 4’s transferStudents is exactly the special case where T is pinned to Concession.

A note on the spec tags

This practical writes @require / @ensure (no trailing s), and uses \result for the return value and \old(x) for a parameter’s pre-call state. The course uses both spellings: @requires / @ensures in the specification tag table and the exam preparation material, and the -s-less forms in the SOLID contracts and this prac. \result is used in the SOLID contracts too. Follow whatever the sheet in front of you uses; see java-specification for the tags themselves.

Task 4’s @ensure clause writes bus.getCurrentCount with the parentheses missing. That is a slip in the practical solution.

Lambdas and Streams

Applied class for 2026-05-21-correct-programming (Week 12). Extends java-lambdas-and-streams (Week 11) with practice reading λ-function traces and standard functional interfaces (Function, BiFunction, Predicate, Supplier, Consumer, BiConsumer, UnaryOperator).

On the HTML site, fill in each blank with your answer as a quoted string (e.g. "6", "Hello World"), then click Run Code to check it. Interactive checking needs a browser, so the blanks do not appear in the PDF; the collapsed Working callout under each task holds the answer either way.

§1 \(\lambda\)-functions

In Java, if an implementation of a functional interface is expected, it can be substituted with a \(\lambda\) (lambda) function. \(\lambda\)-functions take three forms — the general shape on top, a concrete instance boxed beneath it:

Figure 56: The three lambda-function forms, one per column: the general form on top and a boxed concrete example below it.

Lambdas are short-hand for an implementation of a functional interface — an interface with only one method. A motivating example:

interface GrabData<T> {
    void takeThis(T data);
}

class LambdaExample {
    public <T> void distributeData(List<T> data, GrabData<T> grabber) {
        for (T element : data) {
            grabber.takeThis(element);
        }
    }
}

To supply a GrabData<T> you can take the traditional approach and write a named class:

class PrintData<T> implements GrabData<T> {
    public void takeThis(T data) {
        System.out.println(data);
    }
}
...
List<String> words = List.of("alpha", "bravo", "charlie", "delta");
distributeData(words, new PrintData<>());

The diamond matters: a bare new PrintData() is the raw type.

…or use a \(\lambda\)-function, which is the same implementation with the class, its name and the method signature deleted:

List<String> words = List.of("alpha", "bravo", "charlie", "delta");
distributeData(words, (data) -> {
    System.out.println(data);
});

This is much more concise, and encourages using functional interfaces throughout the code base.

The tasks below use the standard functional interfaces from java.util.function. Each has a single abstract method, and the Used in column lists the tasks that use it:

Interface Abstract method Used in
Function<T, R> R apply(T) Tasks 0, 2, 3, 6, 8, 9, 10, 13, 14
BiFunction<T, U, R> R apply(T, U) Tasks 5, 13
UnaryOperator<T> T apply(T) Tasks 7, 14
Predicate<T> boolean test(T) Task 4
Supplier<T> T get() Tasks 1, 12, 13
Consumer<T> void accept(T) Tasks 11, 12
BiConsumer<T, U> void accept(T, U) Task 12

Task 0. What is printed by:

Function<Integer, Integer> f = x -> 2 * x;
System.out.println(f.apply(3));

6

Task 1. What is printed by:

Supplier<String> c = () -> "Hello World";
System.out.println(c.get());

Hello World

Task 2. What is printed by:

int power = 3;
Function<Integer, Double> g = x -> Math.pow(x, power);
System.out.println(g.apply(5));

125.0 (\(5^3\))

Task 3. What is printed by:

int power = 3;
Function<Integer, Double> g = x -> Math.pow(x, power);
power = 2;
System.out.println(g.apply(5));

Does not compile — power is reassigned after the lambda captures it, so it is not effectively final, which lambdas require of any local variable they capture.

Task 4. What is printed by:

Predicate<Integer> p = x -> x % 2 == 0;
System.out.println(p.test(4));

true

Task 5. What is printed by:

BiFunction<Integer, Integer, Integer> add = (x, y) -> x + y;
System.out.println(add.apply(3, 5));

8

Task 6. What is printed by:

Function<String, Integer> strLength = String::length;
System.out.println(strLength.apply("Hello"));

5 — String::length is a method reference, equivalent to s -> s.length().

Task 7. What is printed by:

UnaryOperator<Integer> square = x -> x * x;
System.out.println(square.apply(4));

16

Task 8. What is printed by:

int base = 2;
Function<Integer, Double> exp = x -> Math.pow(base, x);
System.out.println(exp.apply(3));

8.0 (\(2^3\))

Task 9. What is printed by:

Function<Integer, Integer> factorial = n -> {
    int result = 1;
    for (int i = 2; i <= n; i++) {
        result *= i;
    }
    return result;
};
System.out.println(factorial.apply(4));

24 (\(4! = 4 \times 3 \times 2 \times 1\))

Task 10. What is printed by:

Function<Integer, Integer> f1 = x -> x + 1;
Function<Integer, Integer> f2 = x -> x * 2;
Function<Integer, Integer> composed = f1.andThen(f2);
System.out.println(composed.apply(3));

8 — andThen runs f1 first (3 + 1 = 4), then f2 on that result (4 * 2 = 8).

Task 11. What is printed by:

List<Integer> numbers = new ArrayList<>();
Consumer<Integer> addTo = (number) -> numbers.add(number);

addTo.accept(24);
addTo.accept(42);
System.out.println(numbers);

{24, 42}

Task 12. What is printed by:

Supplier<StringBuilder> supplier = StringBuilder::new;
BiConsumer<StringBuilder, String> appender = StringBuilder::append;
Consumer<StringBuilder> printer = System.out::println;

StringBuilder sb = supplier.get();
appender.accept(sb, "cher");
appender.accept(sb, "ryp");
appender.accept(sb, "ick");
printer.accept(sb);

cherrypick

Task 13. What code snippet replaces ??? so this prints 10?

BiFunction<Integer, Function<Integer, Integer>, Supplier<Integer>> g =
    (i, f) -> ??? ;
System.out.println(g.apply(5, x -> x * 2).get());

() -> f.apply(i) — g returns a Supplier<Integer>, a zero-argument lambda that, when later called via .get(), applies f to i (5 * 2 = 10).

Task 14. What is printed by:

Function<Integer, Integer> f = x -> x * 2;
UnaryOperator<Integer> g = x -> x + 1;
Function<Integer, Integer> h = f.andThen(g).andThen(f).andThen(g);
System.out.println(h.apply(3));

15 — chained left to right: f(3)=6, g(6)=7, f(7)=14, g(14)=15.

How a chain of andThen runs

andThen reads left to right: a.andThen(b) means “run a, then feed its result into b”. Task 14’s four-link chain traced out:

Figure 57: Task 14’s chain h = f.andThen(g).andThen(f).andThen(g) evaluated at 3, with the value passed between each pair of stages. The stages apply left to right and the answer is 15.

The trap is reading f.andThen(g) as \(f \circ g\) — it is the other way round, \(g \circ f\). (Function also has a compose method that does go the other way, but none of these tasks use it.)

Task 10 is the same idea with one link: f1.andThen(f2) on 3 gives 3 + 1 = 4, then 4 * 2 = 8.

§2 Streams

In Java, most built-in collections can be converted to a stream for processing, and lambdas tend to be very useful in applying transformations to streams. See java.util.stream.

TipA note on how the answers are written

List results are written with set braces throughout — {2, 4, 6, 8}, and {24, 42} back in Task 11. A real List prints with square brackets: [2, 4, 6, 8]. Every Working callout that reports a list — Task 11 above, and Tasks 15 and 16 below — uses the brace notation, and the checkers accept either form.

Task 15. What is the value of:

Stream.of(1, 2, 3, 4, 5, 6, 7, 8).filter(x -> x % 2 == 0).toList();

{2, 4, 6, 8}

Task 16. What is the value of:

Stream.of(1, 2, 3, 4, 5, 6, 7, 8).map(x -> x * x).toList();

{1, 4, 9, 16, 25, 36, 49, 64}

Task 17. What is the value of:

List<String> list = Arrays.asList("apple", "banana", "cherry");
list.stream()
    .map(String::toUpperCase)
    .filter(s -> s.startsWith("A"))
    .forEach(System.out::println);

APPLE — only "apple" survives the startsWith("A") filter once upper-cased.

Task 18. What is the value of:

Stream<Integer> stream = Stream.iterate(1, n -> n * 2).limit(5);
Integer result = stream.reduce(0, (a, b) -> a + b);
System.out.println(result);

31 — Stream.iterate(1, n -> n * 2).limit(5) produces 1, 2, 4, 8, 16, and \(1+2+4+8+16 = 31\).

Task 19. Convert the following method into streams:

static int sumOfSquareNumbers(List<String> words) {
    int sum = 0;
    for (String word : words) {
        if (word.matches("[0-9]+")) {
            int number = Integer.parseInt(word);
            if (Math.sqrt(number) == Math.floor(Math.sqrt(number))) {
                sum += number;
            }
        }
    }
    return sum;
}
static int sumOfSquareNumbers(List<String> words) {
    return words.stream()
        .filter(word -> word.matches("[0-9]+"))
        .mapToInt(Integer::parseInt)
        .filter(number -> Math.sqrt(number) == Math.floor(Math.sqrt(number)))
        .sum();
}

The hint for this task points at filter, map, mapToInt, reduce and sum. Each if becomes a filter, the Integer.parseInt step becomes a mapToInt, and the sum accumulator becomes the terminal sum().

mapToInt (rather than map) is what makes the last step available: it produces an IntStream, which has sum(); a Stream<Integer> does not, and would need .reduce(0, Integer::sum) instead.

The return is required: a body that starts with words.stream() and no return would not compile for an int-returning method.

Task 20. What does this print?

List<String> words = Arrays.asList("cat", "dog", "elephant", "giraffe");
String details = words.stream()
        .reduce("", (word1, word2) -> word1 + "-" + word2);
System.out.println(details);

-cat-dog-elephant-giraffe — the identity "" is the first word1, so even the first element gets a leading - prepended.

Task 21. What does this print?

Stream<String> stream = Stream.of("hello", "world", "java");
stream.map(String::toUpperCase)
      .forEach(System.out::print);

HELLOWORLDJAVA — print (not println) concatenates every element with no separator.

From loop to pipeline

Task 19 is the one worth re-reading, because the conversion is mechanical once you see which construct maps to which stage. Pairing the two versions up row by row:

Figure 58: Task 19’s imperative method beside its stream solution, with each construct paired to the stage that replaces it. The code is split across rows with the enclosing method signature and braces dropped and intervening lines elided as ...; the last imperative row gathers the three accumulator lines, which are not adjacent in the method. The dashed arrow means is replaced by.

The reusable rule: the loop header becomes the source, each guard becomes a filter, each per-element computation becomes a map, and the accumulator becomes the terminal operation. Task 20’s reduce is the general case of that last step — sum() is just the special case for an IntStream.

Week 13

Course Summary and Exam Preparation

See csse2002 for course logistics. A walk back through the whole course with 52 practice questions attached, plus the shape of the exam.

The practice questions are designed to get you thinking about the content. The actual exam questions will mostly be more challenging.

What is not examinable

Four topics are not examinable:

Topic Where it was taught
Week 03 — Version Control supplementary lecture — java-version-control
Week 10 — No lecture —
Week 11 — Event Driven Programming & GUIs the events half of 2026-05-14-lambdas-streams-and-events
Week 12 — Correct Programming 2026-05-21-correct-programming

So java-hoare-logic, java-loop-invariants and java-events are course content but not exam content. Lambdas are examinable; the events half of the same week is not. Week 12 still gets a practice question, Q52.

Exam structure

15 questions, 100 marks total, 120 minutes plus 10 minutes planning time.

Question Marks Type
Q1–Q8 16 total MCQ
Q9 12 short/long answer
Q10 10 short/long answer
Q11 8 short/long answer
Q12 14 short/long answer
Q13 15 short/long answer
Q14 10 short/long answer
Q15 15 short/long answer

Marks for each question are printed on the paper. Use the planning time to decide the order to attempt questions in, and note any assumptions you make.

Conditions, from the cover sheet

The cover sheet of the paper sets the conditions. The main one:

One A4 sheet of handwritten or typed notes double sided is permitted.

The rest of the cover sheet:

  • Specified written or printed material permitted.
  • Casio FX82 series or UQ approved and labelled calculator only. No other electronic aids — explicitly no laptops, no phones.
  • During planning time, students are encouraged to review and plan responses to the exam questions.
  • Supplied: additional exam materials (answer booklets, rough paper) on request, and 1 × Gradescope bubble sheet (for the MCQ block).
  • “If you believe there is missing or incorrect information impacting your ability to answer any question, please state this when writing your answer.” Marks are awarded out of 100.
  • Two blank pages are added at the end. If you use them, clearly mark which question you are answering, and indicate in the designated answer space that your response continues on the blank pages.

What to expect: what does the code do · what code completes this method · explain concepts · apply concepts · evaluate code · write code.

Preparation advice: review course material — lectures and especially applied classes; practise writing programs by hand (try the Ed Lessons problem-set questions); sample exams are roughly similar in structure and style, with practice exam 3 the most similar; past exams vary in format but have similar question types; and check out the CodeCamps for supplementary material.

Practice questions by week

Week 1 — Java basics

Java is a general purpose programming language: compiled, statically typed, object-oriented, memory safe. Week 1 topics: arithmetic, logical operations, control flow. See java-primitive-and-reference-types.

  1. What is the difference between a statically typed and a dynamically typed language?
  2. What is the output? — int x = 0; while (x < 10) { int x = x + 1; } System.out.println(x);
  3. What is the output? — int x = 6 * 2 - 4; x++; int y = (x % 2) + 3; x *= 3; y += Math.pow(y, 2); System.out.println(x - y);
  4. What is the output? — int x = 3 * 2; while (x < 24) { x *= 2; } int k = switch (x) { case 24 -> x * 3; case 48 -> x * 2; default -> x * 1; }; System.out.println(k);

Week 1 — Collections and strings

A String is a reference datatype constructed from a string literal, e.g. "hello, world". Double quotes create strings; single quotes create chars.

Helpful String methods (not exhaustive):

Signature Meaning
int String.length() Return the length of the string.
char String.charAt(int) Return the char at the given index.
String String.substring(int, int) Return the substring between two indexes.
String String.replace(char, char) Replace occurrences of char with char.
int String.indexOf(char) Return the index of a given char.

For substring, startIndex is inclusive, endIndex is exclusive. Q5 needs this.

Arrays are ordered, fixed-length, mutable sequences of homogeneous items, accessed with [], sized with .length. Collections covered: Stack, List, Set, Map — see java-collections-framework.

  1. What is the output? — String name = "CSSE2002"; int times = name.length() / 4; String result = ""; for (int i = 0; i <= times; i++) { result += name.charAt(i * 2); } result += name.substring(2, 5);
  2. Write contains(int[], int) returning true if the array contains the value.
  3. What is the main difference between an array and a list?
  4. What are two differences between a list and a set?
  5. When would you use a map instead of a set?
boolean contains(int[] array, int value) {
    for (int num : array) {
        if (num == value) {
            return true;
        }
    }
    return false;
}

The enhanced-for body is the answer. The public static modifiers are not part of what was asked.

Weeks 2–3 — OOP

Classes, objects, and the four principles: inheritance, polymorphism, encapsulation, abstraction. The internal state of a class must be protected to avoid leakage. In Java the access modifiers that help are private, public, protected, and default — no keyword required. See java-encapsulation, java-inheritance, java-polymorphism, java-abstraction.

  1. Explain the relationship between classes and objects.
  2. What are the two ways the BankAccount class fails to encapsulate its internal state? (a public int balance field, and getTransactions() returning the mutable internal List<Transaction> — see java-mutability)
  3. When can you assume a class invariant is true?
  4. When is a class invariant allowed to be false?
  5. What differences are there between superclasses and interfaces?
  6. Why would you define a superclass and not an interface?
  7. What is the purpose of overriding a method?

Class invariants must be true after instance construction and after execution of each method invocation. For Q12 and Q13: an invariant must be established after the class constructor; it may be assumed as a precondition of each method (excluding the constructor); and it must be established after each method call. See week8-tutorial-class-invariants.

Q17–Q18 — super and which field gets written
class A {
    private int x = 0;
    public int m() { return  x = 1; }
}
class B extends A {
    private int y = 0;
    public int m() { return  y = 2; }
}
class C extends A {
    private int z = 0;
    public int m() { return super.m(); }
}

A a1 = new B();
A a2 = new C();
a1.m();
System.out.println(a1.m());
System.out.println(a2.m());
  1. What is the value of x after calling a1.m()?
  2. What is the value of x after calling a2.m()?
  • Q17: x is still 0. a1’s actual type is B, so a1.m() runs B.m(), which assigns to B’s own y. A’s x is untouched. B cannot see it anyway, because it is private.
  • Q18: x is 1. a2’s actual type is C, whose m() is return super.m(), i.e. A.m(), which performs x = 1.

The two println lines therefore print 2 then 1.

Q19–Q21 — the Batman overload/override problems

This is the same two-phase rule as the week-4 applied class: the overload is chosen at compile time from the static types, and only then is the override resolved at run time. See java-casting and week4-tutorial-method-dispatch-and-casting.

class Enemy {}
class SuperVillain extends Enemy {}

class BruceWayne {
    public void kapow(Object enemy)       { System.out.println("Smash");  }
    public void bam(SuperVillain enemy)   { System.out.println("Whoosh"); }
}
class Batman extends BruceWayne {
    public void kapow(SuperVillain enemy) { System.out.println("Crunch"); }
    public void bam(Enemy enemy)          { System.out.println("Blam");   }
}
class GeorgeClooney extends Batman {
    public void kapow(Enemy enemy)        { System.out.println("Whack");  }
    public void bam(Enemy enemy)          { System.out.println("Oof");    }
}

The call under test is the same in all three questions:

BruceWayne manBat  = new Batman();
Enemy      poisonIvy = new SuperVillain();
manBat.kapow(poisonIvy);

Q19 — as written above. kapow(Object) is locked in. The static type of manBat is BruceWayne, which declares exactly one kapow, so that signature is fixed at compile time. Batman.kapow(SuperVillain) is an overload, not an override, so nothing displaces BruceWayne.kapow(Object) at run time. The output is Smash.

Q20 (homework) — the parameter type in Batman.kapow(SuperVillain enemy) changes from SuperVillain to Object. So Batman now declares kapow(Object).

Compile time is unchanged: kapow(Object) is still the only signature visible through a BruceWayne variable, so it is still locked in. But Batman.kapow(Object) is now a genuine override of BruceWayne.kapow(Object), so run-time dispatch finds it. Output: Crunch.

Q21 (homework) — the class header changes to class BruceWayne extends Hero {. The new superclass is:

class Hero {
    public void kapow(Enemy enemy) { System.out.println("kapow"); }
    public void bam(Enemy enemy)   { System.out.println("bam");   }
}

kapow(Enemy) is locked in.

Through a BruceWayne variable there are now two applicable kapow overloads — kapow(Object) declared on BruceWayne, and kapow(Enemy) inherited from Hero. The argument’s static type is Enemy, so the more specific kapow(Enemy) wins the compile-time choice. At run time the actual type is Batman, which declares kapow(SuperVillain) — not an override of kapow(Enemy) — so nothing displaces Hero’s version. The output is kapow.

The moral of the three together: adding a superclass changed the answer without touching a single line of the calling code.

CodeCamp — BookShelf / BargainBin

Same idea, different names:

class Book {}
class FictionBook extends Book {}
class CrimeBook   extends FictionBook {}
class RomanceBook extends FictionBook {}
class TextBook    extends Book {}

class BookShelf {
    int cost(Book book)           { return 20;  }
    int cost(TextBook textBook)   { return 200; }
    int cost(CrimeBook crimeBook) { return 30;  }
}
class BargainBin extends BookShelf {
    int cost(RomanceBook romanceBook) { return 2; }
}

public static void main(String[] args) {
    BookShelf shelf = new BargainBin();
    Book theNotebook = new RomanceBook();
    System.out.println(shelf.cost(theNotebook));
}

20. The static type of theNotebook is Book, so the only applicable overload in BookShelf is cost(Book). BargainBin.cost(RomanceBook) is an overload the compiler never even considers, because RomanceBook is not the argument’s apparent type.

The 2025 Sem 2 sample exam asks exactly this as Q1(d) and answers 20 — and then, as Q1(e), changes both declarations to their concrete types:

BargainBin shelf = new BargainBin();
RomanceBook theNotebook = new RomanceBook();
System.out.println(shelf.cost(theNotebook));   // 2

The same kinds of object, declared with different apparent types — a different answer.

Other question types

Given a base class and an interface, you may be asked to create subclasses that implement the interface.

Week 4 — Exceptions and specification

Specification covers Javadoc, restrictiveness, generality, formality, contracts, defensive programming. See java-specification and java-exceptions.

  1. Suggest ways to improve the specification of indexOf in terms of clarity, restrictiveness and generality:

    /**
     * For arrays less than length 5,
     * iterates through the array and if a number matching the given number is found, returns that index.
     */
    public static int indexOf(int[] array, int number) {}

    (The obvious targets: the arbitrary “less than length 5” restriction, and the silence about what happens when nothing matches.)

  2. Same question, different method:

    /**
     * Returns an index (i) of ar such that
     * ar[i] == x, if any
     * else, return -1
     */
    public int search(int[] ar, int x) {…}
  3. Rewrite concat following defensive programming techniques:

    /**
     * Returns the concatenation of two non-null strings.
     *
     * @param first  the left-hand string (must not be null)
     * @param second the right-hand string (must not be null)
     * @return {first} followed by {second}
     * @requiers first != null && second != null
     * @ensures result.equals(first + second)
     */
    public static String concat(String first, String second) {
        return first + second;
    }

    @requiers is a misspelling of @requires. The {first} / {second} brace notation for “the value of this parameter” appears here and nowhere else in the course.

  4. What is printed? — try { print("A"); throw new RuntimeException(); } catch (Exception e) { print("B"); } finally { print("C"); } print("D"); Answer: ABCD. The catch swallows the exception, so finally runs and control then reaches the statement after the try.

Week 5 — Testing and JUnit

Black box · White box · Test Driven Development. See java-testing, java-junit, week7-tutorial-black-box-and-glass-box-testing.

  • Blackbox testing. Smoke tests — does it perform its functionality in the normal use case? Boundary tests — boundary inputs or edge cases which often are poorly handled.
  • Glass/White box testing is used when the software under test is known, and lets you measure coverage: statement, branch, path. Path coverage for loops uses engineers’ induction — 0, 1 and 2 times through the loop.
  1. Provide a set of black box test cases for even, justifying each.

    /**
     * Determines whether a given number is even
     * @param number the integer to be evaluated.
     * @return true if the number is an even number,
     *         false otherwise.
     * @throws NegativeNumberException
     *         if number is negative.
     */
    public static boolean even (int number) {}
  2. Write a JUnit test asserting factorial(5) == 120. Answer:

    public void testFactorialOfFive() {
        int result =  factorial(5);
        assertEquals("Factorial of 5 should be 120", 120, result);
    }
  3. Explain the process of test-driven development.

Figure 59: The TDD cycle: write the test first, watch it fail, write just enough code to pass, then refactor and go round again. The failing state is pink and the passing state is green.

  1. What is the difference between black and glass box testing?
  2. Why is code coverage an important concept?
Q31–Q33 — coverage of register

Q31 and Q32 are the same question on the same code.

public void register(int x) {
    if (x > 0) {
        positives += 1;
    }
    if (x % 2 == 0) {
        evens += 1
    }
}

The line evens += 1 is missing its ;.

Q31 / Q32. Out of statement, branch and path coverage, what is the maximum level of coverage achieved by x = 2?

Q33. Provide a minimal set of inputs that achieve path coverage for register. Justify.

Q31/Q32. x = 2 makes both conditions true, so every statement in the method runs — statement coverage, and no further. Neither if’s false branch is ever taken, so branch coverage (and therefore path coverage) is not reached.

Q33. The two ifs are independent, so there are four paths. One input per path:

Input x > 0 x % 2 == 0 Path
2 T T both counters incremented
1 T F positives only
-2 F T evens only
-1 F F neither

Four inputs, and four is minimal — one per path.

Q34 — path coverage of range, worked in full

This question reappears verbatim as Question 6 of the 2025 Sem 2 sample exam, so it is worth knowing cold.

/**
 * @param array An array of numbers to find the range of.
 * @requires array != null
 * @ensures if array.length > 0 then \result == max(array) - min(array)
 *          otherwise \result == 1
 */
public static int range(int[] array) {
    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;
    for (int i = 0; i < array.length; i++) {
        if (array[i] < min) {
            min = array[i];
        }
        if (array[i] > max) {
            max = array[i];
        }
    }
    return max - min;
}

Provide a minimal set of inputs to the range method that achieves path coverage. Recall that path coverage for loops only requires executing the loop 0, 1, and 2 times.

Figure 60: The decision tree for one iteration of the range loop, together with the initial values of min and max that decide which leaves are reachable. Each leaf is one path through the pair of ifs. The red condition array[0] == Integer.MAX_VALUE names the only value that can take the first if’s F branch, because min starts at Integer.MAX_VALUE. The labels on the left give the array needed to go 0, 1 or 2 times through the loop.

Zero iterations. The loop is not entered: { }.

One iteration — four leaves, one impossible:

Path Input
F F Impossible
F T [Integer.MAX_VALUE]
T F [Integer.MIN_VALUE]
T T [1]

FF needs array[0] == Integer.MAX_VALUE (to fail < min) and array[0] == Integer.MIN_VALUE (to fail > max) at once.

Two iterations — sixteen combinations, of which nine are impossible. Entering the second iteration along the F branch, array[0] was Integer.MAX_VALUE, so max is no longer Integer.MIN_VALUE: it has become Integer.MAX_VALUE, and min is still Integer.MAX_VALUE. That is what makes the FT** rows below come out as they do.

Full path Input
F F F F Impossible
F F F T Impossible
F F T F Impossible
F F T T Impossible
F T F F [Integer.MAX_VALUE, Integer.MAX_VALUE]
F T F T Impossible
F T T F [Integer.MAX_VALUE, 1]
F T T T Impossible
T F F F [Integer.MIN_VALUE, Integer.MIN_VALUE]
T F F T [Integer.MIN_VALUE, Integer.MAX_VALUE]
T F T F Impossible
T F T T Impossible
T T F F [1,1]
T T F T [1,2] or [1, Integer.MAX_VALUE]
T T T F [2,1]
T T T T Impossible

The whole FF** block dies because FF was already impossible on one element. TTTT dies because a second element cannot be simultaneously below the new min and above the new max once both have been set to the first element. Eleven inputs in total — the empty array, three one-element arrays, and seven two-element arrays.

Week 6 — Cohesion and coupling

  1. What is meant by a class having high cohesion? Why might it be desirable?
  2. Explain the meaning of coupling and give an example of the benefits of low coupling.

The contrast is low cohesion with high coupling against high cohesion with low coupling. See java-cohesion-and-coupling and week10-tutorial-coupling-and-cohesion.

Weeks 6–7 — SOLID principles

Applying SOLID principles helps to prevent rigid and fragile software.

  • Single Responsibility — there should never be more than one reason for a class to change
  • Open-closed — components should be open for extension but closed for modification
  • Liskov Substitution — subclasses should be substitutable for their parent classes
  • Interface Segregation — shrink interfaces to minimise incidental dependencies
  • Dependency Inversion — depend on abstractions, not implementations
  1. What is a “responsibility” in the context of the single responsibility principle?
  2. What is prevented by applying the interface segregation principle?
  3. Which SOLID principle is violated by public int sum(ArrayList<Integer> numbers)? Dependency inversion: it names the concrete ArrayList where the List/Collection abstraction would do.
Q40–Q41 — the substitution principle, drawn

Both questions go with the same figure, a way of reasoning about substitutability.

Figure 61: Pre/postcondition funnels. A method is the small box; the cone above it is the set of inputs it accepts (its precondition) and the cone below is the set of outcomes it may produce (its postcondition) — so a wider mouth means a weaker condition. B.f here has a wider top and a narrower bottom than A.f: a legal override.

  1. Do the classes below satisfy the substitution principle?

    class Document {
        /** Returns the next 128 chars of a document. */
        char[] nextChunk() {...}
    }
    class EfficientDocument extend Document {          // should be "extends"
        /** Returns the next 256 chars of a document. */
        @Override
        char[] nextChunk() {...}
    }
  2. Does class B satisfy the substitution principle with respect to class A?

    class A {
        /**
         * @requires x > 0
         * @ensures \result > 'A' && \result < 'Z'
         */
        char process(int x);
    }
    class B extends A {
        /**
         * @requires x != 0
         * @ensures \result > 'J' && \result < 'N'
         */
        char process(int x);
    }

Q41 is a yes. x > 0 implies x != 0, so B accepts everything A did and more — a weakened precondition, which is allowed. And 'J' < r < 'N' implies 'A' < r < 'Z', so every outcome B may produce was already promised by A — a strengthened postcondition, also allowed. That is exactly the shape drawn: wider top mouth, narrower bottom mouth.

Q40 is the harder one. EfficientDocument promises 256 characters where Document promises 128. That is not a strengthening of “the next 128 chars” — it is a different promise, and a caller written against Document that assumes it receives at most 128 will break.

  1. (homework) For each pair, is the second condition stronger, weaker, or neither?

    First Second Verdict
    x > 0 x > -8 weaker
    x != 0 x != 5 neither
    (x != 0) && (x + 7) < 5 (x + 7) < 4 weaker
    (x + y) > 5 (x > 2) && (y > 3) stronger

    The rule: if everything in the first set is also in the second set, the second precondition is weaker, or less strict, than the first.

Q43–Q45 — dependency inversion
  1. Explain how these classes violate the Dependency Inversion Principle:

    class TerminalPrinter {
        /** Draws one black dot at row, column on the terminal. */
        public void typeDot(int row, int column) { /* ... */ }
    }
    class Square {
        private int width;
        private int height;
    
        public Square(int width, int height) {
            this.width = width;
            this.height = height;
        }
    
        public void draw() {
            TerminalPrinter printer = new TerminalPrinter();
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    printer.typeDot(x, y);
                }
            }
        }
    }

    The offending line is TerminalPrinter printer = new TerminalPrinter(); inside draw(). Square both names and constructs the concrete TerminalPrinter, so it depends on an implementation rather than an abstraction, and there is no seam at which another printer could be substituted.

  2. Refactor according to the Dependency Inversion Principle. Answer:

    public interface Printer {
        void typeDot(int row, int column);
    }
    
    public class TerminalPrinter implements Printer {
        @Override
        public void typeDot(int row, int column) {
            System.out.println("Dot: " + row + " " + column);
        }
    }
    
    public class ScreenPrinter implements Printer {
        @Override
        public void typeDot(int row, int column) {
            System.out.println("…");
        }
    }
    
    public class Square {
        private int width;
        private int height;
        private Printer printer;
    
        public Square(int width, int height, Printer printer) {
            this.width = width;
            this.height = height;
            this.printer = printer;
        }
    
        public void draw() {
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    printer.typeDot(x, y);
                }
            }
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Printer printer = new TerminalPrinter();
            Square square = new Square(5, 5, printer);
            square.draw();
        }
    }

    The dependency is inverted: both Square and TerminalPrinter now depend on Printer, and the choice of concrete printer moves out to Main.

  3. (homework) Given that PNGWriter now exists —

    class PNGWriter {
        /** Construct a new PNGWriter */
        public PNGWriter(String path) {...}
        /** Set the x, y pixel within an image to black. */
        public setPixel(int x, int y) {...}
    }

    — use your refactored classes to draw a square of width 8, height 10 to "mysquare.png". You should not need to further modify your refactored classes but may make changes to PNGWriter. That constraint is the point of the exercise: if the Q44 refactor was right, the only change needed is to make PNGWriter implement Printer.

The substitution rule to remember: a subclass may weaken preconditions and strengthen postconditions, never the reverse. See java-solid-principles, week9-tutorial-substitution-principle-and-pre-post-conditions, week11-tutorial-dependency-inversion.

Week 8 — Java I/O

Streams · Readers & Writers · Instance Saving & Loading · New I/O (java.nio.file.*). See java-io.

  1. Write a method public int count(char lookFor, Path file) that counts the number of times a character appears in a file. An answer, taking a File in place of the Path:

    public int count(char lookFor, File file) {
        int count = 0;
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            int currentChar;
            while ((currentChar = reader.read()) != -1) {
                if (currentChar == lookFor) {
                    count++;
                }
            }
        } catch (IOException e) {
            System.err.println("Error reading the file: " + e.getMessage());
        }
        return count;
    }

    Two things to notice: read() returns an int, not a char, precisely so that -1 can signal end-of-stream; and the reader is opened in a try-with-resources header so it is closed on every path out.

  2. What is the difference between an InputStream and a BufferedInputStream?

  3. What is the purpose of flush()?

Week 9 — Generics

Why? · Generic Types · Bounded Generics and wildcards · Type Erasure. See java-generics.

  1. What is the difference between List<? extends T> and List<? super T>? Answer:

    • List<? extends T> (upper bounded wildcard) — the list can hold elements of type T or any subtype of T; used when you read from the list.
    • List<? super T> (lower bounded wildcard) — the list can hold elements of type T or any supertype of T.
  2. Write a generic, type-safe count method over an array that returns how many times the given value occurs. The method must be type-safe and ensure that the given value is the same type as the array contents.

    Before, the non-generic version:

    public int count(int[] array, int value) {
        int count = 0;
        for (int element : array) {
            if (element == value) {
                count++;
            }
        }
        return count;
    }

    After, the generic version:

    public <T> int count(T[] array, T value) {
        int count = 0;
        for (T element : array) {
            if (element.equals(value)) {
                count++;
            }
        }
        return count;
    }

    The single substantive change is == becoming .equals(): once the element type is a reference type T, == compares identities, not values. Declaring both the array and the value as the same T is what makes it type-safe.

Week 11 — Lambdas

  1. What is a functional interface? Contrast a plain single-method interface —

    public interface TestInterface {
        double getValue();
    }

    — with an @FunctionalInterface that declares two abstract methods, which does not compile:

    @FunctionalInterface
    public interface TestInterface {
        double getValue();
        double getAge();
    }

See java-lambdas-and-streams and week12-tutorial-lambdas-and-streams.

Week 12 — Correct programming (not examinable)

Correctness · Deriving Pre-conditions · Loop Invariants.

  1. What does it mean for a program to be correct?

What a real paper looked like

The 2025 Semester 2 sample exam is worth reading alongside these questions: it is eight questions rather than fifteen, with no MCQ block, but the question shapes are the ones to expect. Its answer sheet opens with a warning — the model answers are “the most straight-forward solution but … far from the best solution. They should not be used as examples of good programming practice.”

Q Marks Shape Answers given
1 10 Five 2-mark traces A.f(4) → 3.46666667, rounded 3.47; d(1234, 10) → {4, 3, 2, 1} and d(10, 2) → {0, 1, 0, 1}; then the two BookShelf/BargainBin dispatch parts, 20 and 2
2 4 Fill three holes in a merge-of-sorted-arrays method γ = array.length, μ = arrays[i].length, ω = i
3 6 Recursion from a piecewise mathematical definition (Eulerian numbers) precondition n > 0 && k >= 0, then a direct three-case recursive implementation
4 10 Code style — justify meaningful names, constants over literals, vertical whitespace; then find four violations and cite line numbers missing Javadoc (line 1); ArrayList used instead of the List interface (1); magic number 256 (3); missing horizontal whitespace around operators (5, 7)
5 12 Liskov substitution reasoning, first abstractly on A.f/B.f, then on a FilingSystem hierarchy see below
6 10 Black-box test table, then minimal path coverage for range — the same range method as Q34 above not answered on the paper
7 14 Implement a specified interface (JollyJumperSpec) from its Javadoc full class given
8 14 Implement a Library interface over a Dewey-Decimal call-number scheme full class given

Two of those are worth naming: A.f computes a partial sum of the Leibniz series for π, and d(n, b) returns the digits of n in base b, least significant first. The answer sheet gives only the numeric answers.

Question 5 is the clearest statement of the substitution rule anywhere in the course materials. Its three answers:

  • Given a.f(5) satisfies A.f’s precondition, what do we know about b.f(5)? — “We know that the call to B.f will satisfy the precondition … the precondition of a subclass must be weaker than or equal to the precondition of the superclass.”
  • Given a.f(5) == 10 satisfies A.f’s postcondition, what about b.f(5) == 10? — “May or may not. It is possible for the postcondition of B.f to be stronger than the postcondition of A.f, therefore 10 may not be a valid return value for B.f.”
  • Given a.f(5) == -10 violates A.f’s postcondition, what about b.f(5) == -10? — “We know that the postcondition of B.f will be violated … the postcondition cannot be weakened.”

And parts (d)–(f), on a worked hierarchy: weakening @requires name != null to true satisfies LSP; modifying a postcondition “in an incompatible way” violates it; strengthening a precondition “to include an additional requirement” violates it.

Closing

“I hear and I forget. I read and I remember. I do and I understand.” — Confucius (according to popular belief)

Reference material

CSSE2002 Diagram & Notation Conventions

The house style for every figure drawn in CSSE2002 — inferred from the lecture decks themselves, because this course ships no written notation guide.

How this note was built

The anchor manifest for csse2002 lists 12 lecture decks, 656 pages, and an empty guides array. There is no style guide, no drawing standard, no “how to draw a class diagram” handout. Every convention below is inferred from the drawings, not quoted from a rule. Where a convention rests on a single figure, the entry says so.

Pages actually read

I read 210 of the 656 pages as rendered images, sampled to go wide across the semester and to land on pages that carry drawings rather than bullets:

Deck Pages read of
L01a Course Overview 18–27 62
L01b Java Basics, Collections & Strings 31–42 77
L02 Object Oriented Programming I 1–20, 31–45 54
L03 OOP II & Specification 14–31 62
L04 Exceptions & Specification 6–36 49
L05 Testing 3–14 42
L06 Refactoring, Cohesion & SOLID I 15–32 52
L07 SOLID Principles II 14–30 39
L08 Java I/O 3–16 50
L09 Generics in Java 19–33 46
L11 Lambdas, Streams & Events 20–32 34
L13 Course Summary & Exam Prep 26–40 89

I did not read: L01a 1–17 & 28–62, L01b 1–30 & 43–77, L02 21–30 & 46–54, L03 1–13 & 32–62, L04 1–5 & 37–49, L05 15–42, L06 1–14 & 33–52, L07 1–13 & 31–39, L08 1–2 & 17–50, L09 1–18 & 34–46, L11 1–19 & 33–34, L13 1–25 & 41–89. A few citations below (textbook mentions, “Further Reading” slides) come from extracted text on pages I did not view as images; those are marked (text only). Font names come from pdffonts; hex colours were sampled from rendered pixels, not from any stated palette.

Citations use the form L07 p29 = the deck for lecture 07, PDF page 29.


1. The page frame every figure sits in

Template A — the course template. White ground. Slide title in UQ purple #4E247F, set in Tw Cen MT (a geometric sans), left-aligned at roughly x = 7% and y = 15%. An optional second title line sits directly beneath in smaller magenta #9D0792 / #A02B93 Tw Cen MT. Body prose is Bell MT (a serif) in near-black #171717, round bullets, up to four indent levels with decreasing size. UQ crest bottom-left; solid purple CSSE 2002 badge bottom-right; page number immediately left of the badge in small grey serif.

Cited: L02 p2, p14; L04 p12; L06 p20; L07 p14; L08 p5; L09 p33; L13 p39. Holds across 11 of the 12 decks, weeks 1–13.

Template B — the guest deck. L11 alone uses a completely different template: Raleway Bold black titles, Source Sans Pro black body, hyphen bullets, teal underlined links, occasional full-bleed purple block, and no crest, no badge, no page number. Cited: L11 p20, p23, p24, p28, p31. Seen only in L11 — see Inconsistencies.

Section dividers. Purple Tw Cen MT heading alone, placed low-left or low-centre, everything else blank. Cited: L02 p34, p43, p44; L06 p16, p19, p26; L09 p20, p23, p32; L13 p31, p32, p38. Throughout.

Deck title slides. Centred stack: deck title in purple Tw Cen MT → “Programming in the Large (CSSE2002)” in purple Bell MT → “Dr. Thilina Halloluwa” in black Bell MT → “Week NN – Part NN” in black Bell MT. Cited: L02 p1; L04 p19; L06 p15. Consistent wherever a title slide appears.

2. Typeface roles

Role Face Evidence
Slide titles, section headings Tw Cen MT, purple everywhere in Template A
Prose, captions, labels on the lecturer’s own diagrams Bell MT (serif) L03 p27; L06 p21; L07 p16
Java source; Java identifiers inline in prose; text inside class/dependency boxes Inconsolata (hand-set) or Courier New (pasted) L02 p32, p36; L07 p27; L08 p6
Borrowed / stock figures Arial or similar sans L02 p15; L06 p17; L08 p3; L09 p27

Inline Java identifiers in serif prose are always switched to monospace: byte, char, BufferedInputStream, java.io.InputStream, instanceof, ? extends T. Cited: L03 p29; L08 p15; L09 p24, p30. Very consistent.

3. What colour means

Colour Sampled hex Meaning Evidence Consistency
UQ purple #4E247F chrome, slide titles; nothing semantic inside a figure everywhere throughout
Teal #156082 every relationship line, connector and pointer the lecturer draws L03 p27; L04 p7; L06 p18, p20, p21; L08 p7, p11, p14; L09 p25, p29; L13 p27 strongest colour convention in the course — weeks 3–13
Magenta #9D0782 – #A02B93 subtitle line; a term being defined; a verdict on an example L02 p35; L04 p27, p30; L05 p5; L08 p5, p8; L09 p21, p27, p30 very consistent
Pure red #FF0000 a hard rule to memorise; the outline of a code-highlight box; deadlines L01a p24; L02 p38, p40; L03 p28; L04 p14; L07 p15, p20; L08 p16 consistent for “stop and look”
Green #3B7D23 (Javadoc), bright green (chart) Javadoc/comment text in code; passing tests in the one chart L04 p27; L05 p5 chart usage is a single instance
Near-black #171717 prose, box outlines, arrows in borrowed figures L05 p6, p8; L07 p26 throughout

Nothing anywhere in any deck states what a colour means. Teal-for-relations and magenta-for-defined-terms are inferred from repetition alone.

Cube outline colours in the coupling/cohesion figures (purple #7030A0, red #FF0000, green #196B24, cyan #00B0F0, orange) carry module identity only — the same colour means “same module”, not any property of it. Cited: L06 p18, p20, p27; L07 p24.

4. Class-hierarchy diagrams — the dominant style

Style H1 (dominant). Node = rectangle, thin border, white fill, class name centred in Bell MT serif (not monospace). Superclass sits above. Connector is a teal orthogonal polyline: one vertical stub rising into the parent’s bottom edge carrying a single solid teal arrowhead, a horizontal teal bus, and vertical drop-legs to each child. One arrowhead per parent, not per child. No edge labels, no multiplicities, no stereotypes.

Cited: L04 p7 (Throwable → Error, Exception → RuntimeException, IOException), L08 p7 (OutputStream tree), L08 p11 (InputStream tree). Three figures, two decks, weeks 4 and 8. This is the closest thing the course has to a settled hierarchy notation — but see Inconsistencies for two rival styles.

5. UML-style class boxes (lecture 02 only)

Three compartments separated by thin horizontal rules: name / attributes / operations. Thin black border, white fill, monospace throughout. Name centred and bold-ish; attribute and operation lines left-aligned.

  • Visibility prefix: - private, + public. No # or ~ appears anywhere.
  • Attribute line: - name : String, -hourlyRate: double.
  • Operation line: +getName():String, +logHours(hours:int) : void. Parameters written name:Type, return type after the closing paren’s colon.
  • Constructors live in the operations compartment, written +Employee (name:String, address:String) with no return type.
  • Generalisation: solid black line, unfilled triangle arrowhead at the superclass, orthogonal routing, superclass above.

Cited: L02 p12, p13 (two-compartment variant), L02 p36 (the full hierarchy — the canonical figure), L02 p37, p38, p40.

This notation appears in lecture 02 and nowhere else I read. L09 p21 shows a small corner decoration in a similar spirit, but it is a borrowed graphic in a different palette (pale blue-grey fill, sans labels, + name : string with a lowercase type). Do not treat L09 p21 as course style.

6. Dependency / interface diagrams — the only figures with a legend

These are the only diagrams in the course that draw their own key on the slide, so this is the most reliable convention in the note.

  • Node = plain rectangle, thin black border, white fill, monospace label that includes the Java keyword: class A, class B, class Z, interface AI, interface BSpec.
  • Members are listed inside the same box, one per line, as + a() — with a space after the +, and no compartment rule separating them from the name.
  • Legend, drawn at the right of the slide:
    • solid line + solid arrowhead → “Uses”
    • dashed line + open arrowhead → “Implements”
  • Direction: an arrow always points from the depender to the thing depended upon. class A ──▶ interface AI = A uses AI. class Z ⇠⇠ — the dashed implements arrow runs from the implementing class to the interface (L07 p27, p29, p30).
  • Layout: clients left, abstractions centre, concrete classes right (L07 p26, p27); or dependents at the bottom with the abstraction above (L07 p29, p30). Flow is left→right for “uses” and bottom→top for “implements”.
  • An arrow may terminate on an individual member row inside a box, not only on the box edge (L07 p26).

Cited: L07 p26 (legend shows “Uses” only), L07 p27, p29, p30 (full legend). Four figures, one deck, week 7.

Note the divergence from standard UML: UML draws realisation as a dashed line with a hollow triangle and dependency as a dashed open arrow. This course draws implements as a dashed open arrowhead and uses as a solid line with a solid head. Follow the course, not UML — but be aware you are diverging.

7. The pre/postcondition “funnel” figure

A distinctive, course-specific idiom for reasoning about the Liskov Substitution Principle:

  • A method is a small square box, thin black outline, monospace name (A.f, B.f).
  • Above it, a cone that narrows downward into the box. Its wide upper ellipse is the set of inputs the method accepts — the precondition.
  • Below it, a cone that widens downward out of the box. Its wide lower ellipse is the set of outcomes it may produce — the postcondition.
  • Width = weakness. A wider top mouth = a weaker (more permissive) precondition. A wider bottom mouth = a weaker (less committal) postcondition. So a legal subclass override has a top mouth at least as wide and a bottom mouth no wider than its parent’s.
  • Labels preconditions and postconditions in lowercase serif at the far left of the slide, vertically aligned with the two mouths.
  • Entirely black line art, unfilled, no colour.
  • To compare parent and child, the child’s cones are overlaid on the parent’s in the same frame in thinner/greyer stroke (L07 p17).

Cited: L07 p16 (A.f vs B.f side by side), L07 p17 (overlaid), L07 p18 (reused as a thumbnail). Three pages, one deck.

8. Coupling and cohesion figures

  • A module is an isometric wireframe cube — outline only, no fill, hidden edges dashed. One colour per module, identity only.
  • Coupling is a teal double-headed arrow between cubes. High coupling = many crossing arrows; low coupling = each cube attached by one short teal double arrow to a horizontal grey bar standing for a shared interface.
  • Cohesion uses the same cubes flattened. Low cohesion = colours scattered; high cohesion = same-coloured cubes grouped inside a rectangle outlined in that same colour.
  • Comparison layout: the bad case on the LEFT, the good case on the RIGHT, each labelled with one serif word beneath (High/Low, Low/High).

Cited: L06 p18 (tangled), L06 p20 (High vs Low coupling), L06 p27 (Low vs High cohesion); reused verbatim in L07 p24. Two decks, weeks 6–7.

9. The coupling-levels ladder

Seven identical rectangles — thin black border, white fill, serif label — stacked vertically with even gaps. Ordered most-coupled at the top (Content) down to least at the bottom (None). A single long thin teal arrow points downward to the right of the stack. Its endpoints are captioned in magenta serif with a parenthetical gloss: “Tightly Coupled (Needy)” at the top, “Loosely Coupled (Independent)” at the bottom.

Cited: L06 p21; reused verbatim L07 p25. Two decks.

10. Annotating code

  • Highlight a token: a thin red #FF0000 rectangle drawn around it. Cited: L02 p38, p40; L03 p28; L04 p14; L08 p16. Dominant across four decks.
  • Point at a token: a thin teal straight or diagonal line with a small solid arrowhead, running between the token and a serif caption placed outside the code block, unboxed. Cited: L02 p16; L03 p24, p28; L08 p14; L09 p25, p29; L13 p27. Weeks 2–13 — very consistent.
  • Show a replacement: strike through the token being removed and put the replacement beside it in red. Cited: L02 p4; L07 p20; L13 p27.
  • Mark an error inline: a red squiggly/dashed underline, IntelliJ-style. Cited: L09 p22.
  • Aside / rule-to-remember: a short sentence centred beneath the content in serif — sometimes inside a thin rectangle, sometimes bare. Cited (boxed black): L02 p31; L07 p24; L08 p5; L09 p26. Cited (boxed teal): L03 p21. Cited (unboxed): L03 p23; L06 p31; L08 p12, p15; L07 p14, p25. Inconsistent — see below.
  • Yellow highlighter behind a heading inside a worked-example box. Cited: L07 p19 (single instance).
  • Verdict on an example, placed in the right margin in magenta serif: “Bad Example”, “Better / Still Bad ☹”, “Does not satisfy specification!”, “Satisfies specification!”. Cited: L04 p26, p27, p28, p29, p30, p31. Consistent within L04.

11. Code blocks

Java is shown as light-theme IntelliJ IDEA output, confirmed by the sampled hex values: keywords #0033B3 blue, fields/constants #871094 magenta, strings and Javadoc #3B7D23 green, comments grey italic, annotations (@Override, @Test, @Before) olive/mustard, numeric literals blue. Cited: L02 p4, p16; L04 p22; L06 p24; L09 p22.

Some slides show real IntelliJ inlay hints (3 usages, accountNumber:) and even an editor error popup, i.e. they are screenshots rather than set text. Cited: L02 p5, p6, p9, p20.

Container: either bare on white, or inside a thin black rectangle. Two files at once are shown as two overlapping black rectangles, z-order indicating which is in front. Cited: L02 p39, p41, p42; L03 p16; L04 p13, p18; L07 p18.

A trace puts line numbers in the left margin in monospace and expected results in a right-aligned column of // comments. Cited: L01b p40, p41.

12. Specification / Javadoc notation

The course’s specification “algebra” lives inside Javadoc comments, not in a separate formalism.

  • Javadoc opens /** and closes */, sits immediately above the thing documented, and tags begin with @. Cited: L04 p21.
  • The tag table (L04 p23) is set as a two-column list with no rules: tag name in monospace, its argument placeholder in italic serif, gloss in upright serif.
Tag Argument Meaning (as printed)
@param varname … Describe a parameter for a method
@return … Describe the return value
@throws ExceptionType … Describe when a particular exception is thrown
@requires Precondition Specify the assumptions for a method to execute properly
@ensures Postcondition Specify the effects of executing the method
@author authorname Specify the author of the class
@copyright … Provide details on who owns copyright
  • \result denotes the returned value inside a postcondition. Cited: L07 p18, p19, p20.
  • Conditions are written in Java boolean syntax, not mathematical notation: row != null && col != null && 0 < val && val < 100. No ∧, ∀, ⟹ appears anywhere I read. Cited: L07 p18; L13 p36.
  • {param} braces denote a parameter’s value inside prose in a tag: @return {first} followed by {second}. Cited: L13 p36 (single instance).

13. Arrays and stacks

Array. A horizontal row of equal-width square cells sharing thin black borders; values centred; no index row. An empty cell is a hole. A grey ghosted digit is a value being shifted out. ? is an unspecified value. A purple curved arrow drawn above the row = one shift-left step. Cited: L01b p31–p37 (a seven-frame build). A second, smaller variant puts the array’s name in monospace immediately to the left of the row and sets the values in serif: L04 p27.

Stack. Cited: L01b p39 — an open-topped U-shaped container in bright purple #6B088F (no top edge), entries as purple-filled rounded rectangles with white bold numerals, growing upward so the top of stack is at the top. A grey curved arrow into the container = push; a grey curved arrow out and away = pop. Each frame is captioned in monospace with the operation (empty(), push(1), pop()), and frames read left→right as time.

14. Black-box / glass-box testing icon

A grey-filled isometric cube, unlabelled, with a black horizontal arrow entering on the left labelled input in serif above the line, and a matching arrow leaving on the right labelled output. Flow is strictly left→right. The glass-box variant is the same cube rendered translucent with the source code visible inside it. Cited: L05 p6 (both cubes together), L05 p8 (black-box cube reused as a corner marker).

15. Attribution and textbook lineage

No figure anywhere I read carries a “Figure from …” caption, and no single textbook governs the drawing style. The course cites books for content, never for notation.

Placement convention: a source line sits at the top of the slide, right-aligned, small serif, no box and no rule.

  • “Effective Java (2017) - Item 75: Include failure-capture information in detail messages” — L04 p8
  • “Java: The Complete Reference, Eleventh Edition- Herbert Schild” — L08 p4
  • “Effective Java, Item 31: parameterized types are invariant; List<Type1> is neither a subtype nor supertype of List<Type2>” — L09 p28
  • “Effective Java (2017, Addison-Wesley) - Item 9” — L08 p20 (text only)
  • Bare URLs in the same position: L01b p38; L05 p5, p9; L08 p9, p10; L09 p26.

Borrowed figures carry an adjacent link instead: “Source : Javatpoint” in small serif at the figure’s lower right (L08 p3); a bare hyperlink reading just “source” centred beneath the figure (L06 p28).

A book cover can stand in for a citation: L03 p15 shows the Effective Java 2nd edition cover as the whole visual for the slide.

Books named in prose (text only — pages not viewed as images): Martin Fowler, Refactoring: Improving the Design of Existing Code (2nd edition, 2019) and Robert Martin, Clean Code at L06 p14; Robert C. Martin, Design Principles and Design Patterns at L06 p35 & p50, L07 p3, L07 p38; Effective Java items at L03 p18, p22 and L04 p47.

16. Naming and capitalisation

  • Java identifiers follow standard Java: PascalCase types, camelCase methods and fields, SCREAMING_SNAKE constants, always monospace. Consistent everywhere.
  • Running example names: Person, Employee/ContractEmployee/ FullTimeEmployee, Animal/Dog/Cat, BankAccount/AccountHolder, Foo, Printer, and for abstract structural examples class A/B/C, class Z, interface AI/BI/CI, interface BSpec.
  • Interfaces in structural diagrams are named either <Letter>I (AI, BI, CI — L07 p27) or <Class>Spec (BSpec — L07 p29, p30). Both in the same deck.
  • Method-signature shorthand in prose uses UML order — getType():String, addListener(String type, Consumer<SimpleEvent> action): action (L11 p28) — while diagram boxes use the same order (L02 p36). Consistent.
  • A right arrow → in serif means “resolves to” / “dispatches to”: kapow(Object) → locked in. Cited: L13 p26, p28.
  • ASCII -> between monospace type names means “widens to” in the casting chains: byte -> short -> char -> int -> long -> float -> double. Cited: L03 p26.

Inconsistencies

Where the course does the same thing more than one way. A decision is needed on each of these before drawing a new figure — I am recording both, not choosing.

  1. Three different ways to draw inheritance.

    • H1 — black-outlined box, serif class name, teal orthogonal connector, plain solid teal arrowhead into the parent, no edge label: L08 p7, L08 p11.
    • H2 — UML: black-outlined three-compartment box, monospace name, black orthogonal connector, unfilled triangle arrowhead: L02 p36, L02 p40.
    • H3 — black-outlined box, serif name, teal diagonal (not orthogonal) lines, plain arrowhead, and every edge labelled “Is a” / “Is an” in serif: L03 p27. All three put the superclass above. They disagree on arrowhead shape, on routing, and on whether edges are labelled. Decision needed.
  2. Hierarchy box border colour. Purple #4E247F at L04 p7 versus black #171717 at L08 p7 and L08 p11 — same figure type, four weeks apart.

  3. Class name typeface inside a box. Serif at L04 p7, L08 p7, L08 p11; monospace at L02 p36, L07 p27, L07 p29.

  4. Where the class name goes. Inside a dedicated name compartment at L02 p36; floating above an unlabelled two-compartment box as “Person Class” at L02 p12 and L02 p13 — within one deck.

  5. Specification tag spelling — three variants.

    • @requires / @ensures — L04 p23 (the tag table itself), L13 p36 (which additionally misspells it @requiers).
    • @require / @ensure (no s) — L07 p18, p19, p20, used consistently across that whole deck’s worked example.
    • @returns instead of @return — L05 p8. Decision needed. The tag table (L04 p23) and the exam-prep deck (L13 p36) agree on the -s forms; the SOLID deck (L07) does not.
  6. Spacing inside UML member lines, within one figure (L02 p36): - name : String (spaces both sides of the colon) in the Employee box, but -hourlyRate: double (no leading space, none before the colon) in ContractEmployee. Likewise +getName():String versus +logHours(hours:int) : void versus +printDetails() : String.

  7. Code-highlight rectangle colour. Red at L02 p38, L03 p28, L04 p14, L08 p16; purple at L02 p16 and L02 p17; plain black at L08 p14.

  8. The “translates to / produces” block arrow. Solid teal block arrow pointing right at L02 p13 (UML box → code); hollow black-outlined block arrow pointing down at L05 p10 (class → test class); solid black block arrow pointing right at L06 p17 (monolith → modular). Same semantic role, three renderings.

  9. Aside / rule boxes. Thin black rectangle at L02 p31, L07 p24, L08 p5, L09 p26; thin teal rectangle at L03 p21; no box at all at L03 p23, L06 p31, L07 p14, L08 p12, L08 p15 — all carrying the same kind of one-line rule-to-remember.

  10. Two stack renderings inside one deck. L01b p39: purple open-topped container, purple filled blocks, grey push/pop arrows, monospace operation captions. L01b p40 & p41: white cells with black borders and a heavy bottom rule, quoted string values in bold sans, variable name in monospace below the stack, no container and no arrows.

  11. Two array renderings. L01b p31–p37: large cells, no name label, sans/mono digits. L04 p27: small cells, serif digits, array name ar in monospace to the left of the row.

  12. Code-block borders. Crisp thin black rectangle (L02 p39, L04 p13); hand-drawn wobbly “sketched” rectangle at L05 p10 and L05 p11 only; or no border at all (L02 p32, L04 p22).

  13. Two whole slide templates. Template A (Tw Cen MT / Bell MT / crest / badge) versus Template B in L11 (Raleway / Source Sans Pro / no chrome). A figure drawn for L11’s week will not match a figure drawn for any other week.

  14. Attribution placement. Top-right of the slide (L04 p8, L08 p4, L09 p28) versus adjacent to the figure itself (L08 p3, L06 p28) versus a cover image standing in for the citation (L03 p15).

  15. Which edition of Effective Java. 2nd edition cover shown at L03 p15; “(2017)” i.e. 3rd at L04 p8 and L08 p20; “(3rd Edition)” spelled out at L04 p47; unlabelled at L03 p18, p22 and L09 p28.

  16. Syntax-colour theme drifts between pasted screenshots. new renders blue #0033B3 at L02 p16 but magenta at L01b p42; some blocks carry IntelliJ inlay hints (L02 p5, p6) and others do not.

  17. Sub-title-line capitalisation. “Levels” at L06 p21 but “levels” at L06 p29; “Byte Stream (Output)” (L08 p7) beside “Abstraction” (L08 p5). Slide titles likewise: “Black Box testing” (L05 p8) versus “Blackbox testing” (L13 p40); “Bounded generics” (L09 p21) versus “Bounded Generics” (L09 p20).

  18. The interface naming scheme. AI/BI/CI at L07 p27 but BSpec at L07 p29 and p30 — two slides apart.

  19. Table styling. The only formal data table I found (L01a p18, the semester schedule) uses a navy header band and pale-blue zebra rows — not the UQ purple used by everything else on the same slide deck.


Not established by the source

Things a new CSSE2002 diagram will plausibly need that the materials simply do not settle. This is where the risk of inventing notation lives.

  • Aggregation and composition. No filled or hollow diamond appears in any page I read. L02 p9 has a code comment reading // Association with AccountHolder, but no diagram of that association is ever drawn. How to show “has-a” is unestablished.
  • Multiplicities. No 1, 0..1, 1..* or * ever appears on an edge.
  • Abstract classes and interfaces in a UML box. No «interface» stereotype, no italicised abstract class name, no dashed realisation triangle. L07 writes the keyword into the label text instead (interface BSpec), but that deck’s boxes have no compartments, so the two idioms cannot simply be merged.
  • Static members. The usual UML underline is never shown.
  • Package or namespace boxes. Never drawn, despite packages appearing in code (L02 p20).
  • Sequence diagrams, state machines, activity diagrams, flowcharts, ER diagrams. None in any of the 210 pages I read.
  • Control-flow graphs. Glass-box testing is taught (L05 p6) and path/branch coverage is implied, but no CFG, decision tree or coverage diagram is drawn. There is no notation for one.
  • Stack-and-heap memory diagrams. The schedule (L01a p18) lists a Week 3 applied class called “Stack & Heap”, but no lecture deck I sampled draws one. Boxes-and-pointers, reference vs value, and how to render null are all unestablished from the lecture materials.
  • Object (instance-level) diagrams. Nothing like p1:Person. The nearest thing is a borrowed clip-art figure at L02 p15 in a completely foreign style (yellow label chips, grey value cards, child cartoons) that should not be copied.
  • Generic types inside a diagram box. <T>, ? extends T and ? super T appear only in code and in a borrowed Number-tree graphic (L09 p27, p31). How to render a parameterised type in a class box is unestablished.
  • Exact palette values. No deck states a hex code. Every colour in this note was sampled from rendered pixels. Line weights, arrowhead sizes and box corner radii are likewise nowhere specified.
  • Dark mode / greyscale printing. Every figure assumes a white ground and colour output. There is no stated fallback, and the coupling/cohesion cube figures (L06 p20, p27) become unreadable in greyscale because colour is the only thing distinguishing modules.
  • Figure numbering and captions. Not one figure in the decks is numbered or captioned “Figure N.” Captions, where they exist, are bare serif phrases beneath the art. There is no established way to cross-reference a figure.
  • Whether new hierarchy figures should be UML-correct. This is the single biggest open question. The dominant house style (H1) uses a plain arrowhead where UML requires a hollow triangle; lecture 02 uses the triangle. Neither is declared canonical.
  • Font substitutes. Tw Cen MT, Bell MT and Inconsolata are the embedded faces, but nothing says what to substitute when they are unavailable.

Java Abstraction

Introduced in 2026-03-05-object-oriented-programming-i (Lecture, Week 2).

What is abstraction?

The ability to hide complex implementation details and expose only the essential behaviours. In Java, abstraction is often implemented using interfaces and abstract classes — both define methods that must be implemented by subclasses, providing a contract that specifies what operations can be performed on an object without specifying how those operations are implemented.

Interfaces

  • An interface is a group of related methods with empty bodies.
  • An interface defines a contract that implementing classes must fulfil.
  • To access the interface methods, the interface must be implemented — and a class can implement multiple interfaces if required.

Interfaces provide abstraction in Java by defining behaviour without specifying implementation.

public interface PaymentProcessor {
    void processPayment(double amount);
}

Any payment processor must have a processPayment() method. Two classes take the interface up, each with its own body for that one method:

public class PayPalProcessor implements PaymentProcessor {
    @Override
    public void processPayment(double amount) {
        System.out.println("Processing PayPal payment: " + amount);
    }
}

public class StripeProcessor implements PaymentProcessor {
    @Override
    public void processPayment(double amount) {
        System.out.println("Processing Stripe payment: " + amount);
    }
}

and the caller is written against the interface, never against either class:

public class Main {
    public static void main(String[] args) {
        PaymentProcessor processor = new PayPalProcessor();
        processor.processPayment(100);
    }
}

The declared type of processor is PaymentProcessor, so Main can only call what the interface promises: the program only interacts with the interface. Swapping new PayPalProcessor() for new StripeProcessor() is therefore a one-line change: it changes what runs without touching anything else in Main.

Figure 62: Main depends on the PaymentProcessor interface, not on either implementation - which is what makes swapping PayPal for Stripe a one-line change. Each rectangle is labelled with its Java keyword and lists its members as + lines. A solid arrow with a solid head means uses. A dashed arrow with an open head means implements and runs from the implementer to the interface. The client is on the left and the abstraction in the centre.

An interface in Java represents an abstraction. It defines a set of behaviours that classes must implement, but it does not define how those behaviours are implemented. The implementation details are hidden inside the classes that implement the interface.

Abstract classes

  • An abstract class is a class that cannot be instantiated.
  • It can contain both abstract methods and fully implemented methods.
  • The abstract keyword is used to declare abstract classes and methods.
  • Subclasses must implement all abstract methods.

One qualification to the first bullet: an instance of an abstract class can be created using an anonymous class. The two statements are consistent. The ban is on new Payment(), while new Payment() { ... } instantiates an anonymous subclass rather than Payment itself.

public abstract class Payment {
    public void validateTransaction() {
        System.out.println("Validating transaction...");
    }

    abstract void processPayment(double amount);
}

That class defines common behaviour for every payment (validateTransaction), and does NOT define how a payment is processed. A subclass supplies the missing half:

public class PayPalPayment extends Payment {
    @Override
    public void processPayment(double amount) {
        System.out.println("Processing PayPal payment: $" + amount);
    }
}

public class Main {
    public static void main(String[] args) {
        Payment payment = new PayPalPayment();

        payment.validateTransaction();
        payment.processPayment(150.0);
    }
}

The abstract class defines the common behaviour of all payments while leaving the specific logic to subclasses. The two calls in main do different things structurally: validateTransaction() runs the body inherited from Payment, while processPayment() runs the body PayPalPayment had to supply.

Interfaces vs abstract classes

A homework / self-study item in Week 2, taken up in 2026-03-12-object-oriented-programming-ii (Lecture, Week 3).

  • Use an interface to define a capability or contract, e.g. Flyable, Runnable, Payable. A class can implement multiple interfaces.
  • Use an abstract class to define a shared base implementation (common behaviour), e.g. an Animal abstract class shared by Dog and Cat. A class can only extend one (super)class.
abstract class Animal {
    public void eat() {
        System.out.println("Animal is eating");
    }
    public abstract void makeSound();
}

class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Dog barks");
    }
}

class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Cat Meows");
    }
}

A class can combine both: extend at most one abstract/concrete class, while implementing as many interfaces as needed:

class Dog extends Animal implements Runnable, Swimmable
class Duck extends Animal implements Flyable, Swimmable

Both mechanisms lean on the same machinery as java-inheritance — the @Override annotation and identical method signatures — and both pay off in Week 3 as java-polymorphism.

Java Casting

Introduced in 2026-03-12-object-oriented-programming-ii (Lecture, Week 3). See also java-primitive-and-reference-types and week4-tutorial-method-dispatch-and-casting.

Casting is the process of converting a variable from one data type to another. There are two kinds: primitive casting, between the built-in numeric types, and reference casting, up and down an inheritance hierarchy.

Primitive casting

Set as self-study (homework). The reading is w3schools’ type casting page.

  • Widening — converting a smaller type to a larger type size: byte -> short -> char -> int -> long -> float -> double.
  • Narrowing — converting a larger type to a smaller size type: double -> float -> long -> int -> char -> short -> byte.

Figure 63: The two primitive conversion chains on a single axis: the narrowing chain is exactly the widening chain reversed. Widening is implicit; narrowing needs an explicit cast.

An example of a narrowing cast: long floatToLong = (long) inputFloat;.

Reference casting

  • Upcasting (implicit) — casting a subclass reference to a superclass reference.
  • Downcasting (explicit) — casting a superclass reference back to a subclass reference.

The two directions are defined against a class hierarchy: up the tree is upcasting, down the tree is downcasting.

Figure 64: The class hierarchy that upcasting and downcasting move along, with ‘Is a’ / ‘Is an’ edge labels and the up/down casting axis at the right. Object sits at the root because every class implicitly extends it.

Upcasting

Upcasting is done implicitly and is always safe: every Cat really is an Animal, so no check and no cast syntax is needed. In the assignment below the Cat is treated as an Animal:

public class Animal {
    public void makeSound() { System.out.println("Animal makes a sound"); }
}
public class Cat extends Animal {
    @Override public void makeSound() { System.out.println("Cat meows"); }
}

Animal myAnimal = new Cat(); // upcasting: Cat is treated as an Animal
myAnimal.makeSound();        // Outputs: Cat meows

After the upcast, the declared type narrows what you may call, but the object still decides which body runs. That is java-polymorphism’s runtime dispatch, and it is why the line above prints Cat meows rather than Animal makes a sound.

Downcasting

Before downcasting, you must ensure the object is an instance of the subclass using the instanceof operator. The cast is written explicitly, and it is the only way to reach members that exist on the subclass but not the superclass:

public class Cat extends Animal {
    @Override public void makeSound() { System.out.println("Cat meows"); }
    public void climb() { System.out.println("I can climb trees"); }
}

public class DownCasting {
    public static void main(String[] args) {
        Animal myAnimal = new Cat();     // upcasting

        if (myAnimal instanceof Cat) {
            Cat myCat = (Cat) myAnimal;  // Downcasting
            myCat.climb();               // access methods specific to cat
        }
    }
}

The instanceof guard is mandatory because an unguarded bad downcast is not a compile error: it compiles and throws ClassCastException at run time (see java-exceptions).

Additional reading: upcasting and downcasting in Java.

Every class implicitly extends Object

Worked question: what is the parent of class Student, a class with no extends clause at all?

public class Student {
    public void study() {
        System.out.println("CSSE2002");
    }
}

The answer is Object, the root of the Java class hierarchy and the top box of Figure 64. So every reference type can be upcast to Object, and a container declared over Object will hold anything. Getting a specific type back out of one means downcasting, which is the problem java-generics exists to remove.

Java Cohesion and Coupling

Introduced in 2026-04-02-refactoring (Lecture, Week 6, Part 2). Practised in week10-tutorial-coupling-and-cohesion.

Modularization

The process of dividing a large system (a monolith) into smaller, more manageable pieces that can be worked on and tested independently before being reassembled into the final product. This raises the question everything below answers: what if the resulting modules are highly dependent on each other? Cutting a monolith into pieces buys nothing if every piece still has to know about every other one. The left panel of the coupling figure below shows exactly that failure: six modules tangled together with arrows in all directions.

Two measures separate a real decomposition from a nominal one: coupling (how much the modules depend on each other) and cohesion (how well the contents of one module belong together).

Coupling

The degree of interdependence between different modules, classes, or components of a system.

  • High coupling — strong interconnections, where a change in one module can cascade through others.
  • Low coupling — greater independence and isolation between modules.

Figure 65: High versus low coupling. Left: every module talks directly to several others, so a change in any one can reach any other. Right: the same six modules each talk only to a shared interface — the grey bar — so nothing propagates further than that bar. A module is a wireframe cube, and its colour only tells the modules apart; a dependency is a teal double-headed arrow. The tangle of arrows on the left is schematic — the count is the point, not which cube joins which.

Levels of coupling (tightly → loosely coupled)

  1. Content — one class directly manipulates another’s data (e.g. public fields instead of private).
  2. Common — sharing access to the same global data/variables.
  3. External — sharing something imposed by an external source, e.g. a data format.
  4. Control — one class controls what happens in another by passing it information/instructions.
  5. Stamp — sharing a data structure, but each class only needs access to a select part of it.
  6. Data — sharing data through means such as parameter passing in methods.
  7. None — no dependency at all (most loosely coupled).

The list is ordered, and the order is the assessable part: the same two classes can be joined in any of these ways, and the further down the list you can get, the less a change in one can force a change in the other.

Figure 66: The coupling-levels ladder. Most tightly coupled at the top, least at the bottom, with the arrow running down from tightly coupled (needy) to loosely coupled (independent).

Worked classification examples

Four snippets, each with the same question: what type of coupling do these methods have? Each answer is reasoned from the definitions above.

public void sinh(int x) {...}
public void cosh(int x) {...}
public void tanh(int x) {
    return sinh(x) / cosh(x);
}

tanh only interacts with sinh/cosh by passing/receiving simple parameters — data coupling.

public class R { int x, y, z; char a, b, c; }
public static void compute(R r) {
    return r.x * r.y; // only touches x and y
}

compute is handed the whole R object but only needs two of its six fields — stamp coupling.

public static void compute(R r) {
    return r.x * r.y * r.z / r.a + r.b + r.c; // uses every field
}

Here every field of R is actually used, so passing the whole object is fully justified — this is just data coupling via a composite value, not stamp coupling (contrast with the previous example, which only used part of the structure).

public static runReport(String name, int age, String phone, Date birth, String address) {...}

Five separate simple parameters — still data coupling, though a long parameter list like this is itself often a separate code smell (see java-refactoring) worth considering bundling into an object.

Cohesion

The degree of interrelatedness and focus among the elements within a module, class, or component.

  • High cohesion — elements are closely related and contribute collectively to one specific functionality.
  • Low cohesion — elements are less focused, serving multiple unrelated purposes.

Asked of a class, cohesion comes down to two questions: how well do the parts of the class (state and methods) fit together? and do they all contribute to a single, clear purpose?

High cohesion is preferable. (Low cohesion usually indicates that a class should be split.)

Figure 67: Low versus high cohesion. The same twelve elements in both panels: on the left the four kinds are scattered across the grid, on the right each kind is gathered into one module. Colour means kind only, and each high-cohesion group is enclosed by a rectangle in that group’s own colour. This figure says nothing about coupling — it is only about what sits inside one module. The good case is again on the right.

Levels of cohesion (low → high)

  1. Coincidental — elements grouped arbitrarily, with no clear relationship.
  2. Temporal — elements grouped because they execute at the same time/phase.
  3. Procedural — elements grouped by their involvement in a specific sequence of steps.
  4. Communicational — elements work together to manipulate a shared data structure.
  5. Sequential — elements organised in a linear sequence, where one’s output is the next’s input.
  6. Functional — elements grouped around a single, specific functionality or task (most cohesive).

Worked example

public void performTasks(int[] numbers, String text) {
    // Task 1: sum the numbers
    int sum = 0;
    for (int num : numbers) { sum += num; }
    System.out.println("Sum of numbers: " + sum);

    // Task 2: reverse the text
    StringBuilder reversedText = new StringBuilder();
    for (int i = text.length() - 1; i >= 0; i--) { reversedText.append(text.charAt(i)); }
    System.out.println("Reversed text: " + reversedText);
}

Summing numbers and reversing text share no real purpose — they’re only in the same method because they happen to run one after another. This is low (coincidental, or at best temporal) cohesion, and a sign performTasks should be split into two focused methods.

Is this class cohesive?

A Car class contains: Fuel, Steering, Speed, Route planner, Public holiday calculator.

Fuel/Steering/Speed are all core to a car’s own physical behaviour, but a route planner and (especially) a public-holiday calculator are unrelated concerns bolted onto the class — this is low cohesion, and a sign the class is trying to do too much (a “God class”); the unrelated pieces should be split into their own classes.

Considerations

  • Classes should be highly cohesive — a single, easily understood concept.
  • Classes should have loose coupling to each other — this reduces overall system complexity.

Good modularization (high cohesion, low coupling) groups tightly-interconnected elements together into the same module and minimises connections between modules, unlike bad modularization, where connections are scattered across module boundaries with no clear grouping. The figure below makes this precise, because both panels are the same system — the same ten elements and the same fifteen dependencies — grouped into modules two different ways:

Figure 68: Bad versus good modularization. Both panels draw the same ten elements and the same fifteen dependencies; only the assignment of elements to modules A, B and C differs. Left: 5 dependencies fall inside a module and 10 cross a boundary. Right: 11 fall inside and only 4 cross. Nothing was rewritten to achieve that — the code is identical, the grouping is not.

Read off the figure, the two measures are the same count seen from opposite sides: a dependency that stays inside a module is cohesion, and a dependency that leaves one is coupling. Maximising the first and minimising the second is one decision — where to draw the boundaries — which is why the goal is always stated as a pair.

Java Collections Framework

Introduced in 2026-02-26-java-basics-part-02-collections-and-strings (Lecture 1, Week 1) — see that lecture for the worked push/pop/add/remove traces. All of these live in java.util.*, and (unlike arrays) grow/shrink automatically.

Why collections instead of arrays?

An array is an ordered fixed-length mutable sequence of homogeneous items, and that costs you two things:

  1. Fixed size at creation. You have to know up front how much space you need.
  2. They do not automatically close gaps. Removing an element from the middle leaves a hole; closing it means shifting every later element down by hand, and the array is still the same length afterwards, so the trailing cell has to be given some filler value.

Collections solve both, at the cost of only being able to store objects (reference types) — see java-primitive-and-reference-types for the primitive wrapper classes (Integer, Double, etc.) used to store primitives inside them.

Stack — LIFO

Method Description
empty() Is this stack empty?
peek() Return the object at the top of the stack
pop() Remove (and return) the object at the top of the stack
push(obj) Put obj on the top of the stack
import java.util.Stack;

Stack<Type> stacks = new Stack<>();

pop() on an empty stack throws EmptyStackException.

Figure 69: Last In, First Out: push always adds at the top and pop always removes from the top, so the last value in is the first value out. The stack is an open-topped container whose entries grow upward. An arrow into the container is a push and an arrow out and away is a pop. Each frame is labelled with its operation, and the frames read left to right as time. In the pop() frame the 3 is lifted clear of the container to show it gone.

List

An interface, not a particular implementation — you can declare a variable as List, but can’t do new List().

  • ArrayList — better for random access (get(i)).
  • LinkedList — better for operations that modify the middle of the list.

Holds items in sequential order (like an array), 0-indexed, with no fixed size limit; supports inserting/removing at any position and checking whether an item is present.

Method Description
add(e) Append e to the end
add(index, e) Insert e at index, shifting everything from index up by one
get(index) Return the element at index
remove(index) Remove the element at index, shifting everything above it down by one

The shifting is the whole point — it is the gap-opening and gap-closing an array makes you write yourself:

Figure 70: add(index, e) on a List: e lands at that index and every entry from there up renumbers, so the list gets longer without you writing a single shift. (remove(index) is the mirror image — see the removal step traced in 2026-02-26-java-basics-part-02-collections-and-strings.) The list has index 0 at the bottom and grows upward, with index cells on the left, values in green on the right, and the variable name in a small box beneath the stack of cells.

Set

Stores unique items (no duplicates); don’t assume any iteration order.

interface Set<E> {
    int size();
    boolean contains(E item);
    boolean add(E e);
    boolean remove(E item);
}

add returns true if the set changed and false if the item was already present — so farm.add("Fox") a second time returns false and leaves size() alone.

  • TreeSet<E> — E must implement Comparable (e.g. String).
  • HashSet<E> — E must have sensible hashCode()/equals().

Map

Stores key → value pairs (like a Python dict) — specify a type for both the key and the value, e.g. Map<Integer, String>. The value type can itself be a collection: Map<String, ArrayList<String>>.

interface Map<K, V> {
    int size();
    boolean containsKey(K key);
    boolean containsValue(V value);
    V get(K key);
    V put(K key, V value);
    V remove(K key);
    Set<K> keySet();
}

put on a key that is already present overwrites its value, so the read-modify-write idiom is m.put(k, m.get(k) + 1). put also returns the displaced value. That is standard Map behaviour, and it is the V return type in V put(K, V).

  • TreeMap<K,V> — K must implement Comparable.
  • HashMap<K,V> — K must have sensible hashCode()/equals().

The hashCode/equals contract

HashSet/HashMap rely on their elements/keys satisfying:

  1. x.equals(y) \(\iff\) y.equals(x) (symmetric).
  2. x.equals(y) \(\implies\) x.hashCode() == y.hashCode().

hashCode() returns an integer generated by a hashing algorithm for the object — two objects that are .equals() must hash the same, or a HashSet/HashMap won’t be able to find them correctly. For example "Thilina".hashCode() is 318621125.

Java Encapsulation

Introduced in 2026-03-05-object-oriented-programming-i (Lecture, Week 2).

Classes and objects

  • A class describes the contents of the objects that belong to it: an aggregate of data fields (properties) plus the operations (methods) defined on them.
  • An object is an element (instance) of a class; objects have the behaviours of their class. The object is the actual component of a running program, while the class specifies how instances are created and how they behave.

Figure 71: One Student class, three Student objects: the class fixes the member variables and methods, each object carries its own values for them. Each arrow is one new Student(…) call creating an object. anu’s average is rounded to 76.6.

Encapsulation

Encapsulation is the process of bundling code (methods/member functions) and data (member variables) together into a single unit — a class. It restricts direct access to some of an object’s components, preventing the accidental modification of data.

Figure 72: What a class is made of, and how it is written as a diagram. Left: a member-variable compartment above a methods compartment, the two braced together as the class. Right: the same idea as a two-compartment box, attributes above operations, with the class name above the box. The attribute list and the operation list in the box do not quite match (email against getAddress).

The Java that box stands for:

public class Person {
    private String name;
    private int age;
    private String email;
    private String[] phoneNumber;

    public Person(String name, int age, String email, String[] phoneNumber) {
        this.name = name;
        this.age = age;
        this.email = email;
        this.phoneNumber = phoneNumber;
    }

    public String getName() { return name; }
    public int getAge() { return age; }
    public String getEmail() { return email; }
    public String[] getPhoneNumber() { return phoneNumber; }
}

The box and the code do not match exactly: the box lists an email attribute but a getAddress() operation (the box has no address attribute and no getEmail() operation, while the code has email and getEmail() and no address at all), and the box spells the array field phoneNumbers where the code spells it phoneNumber. The intended mapping is the obvious one — one private attribute per - line, one public method per + line, the constructor in the operations compartment with no return type.

Constructors

A constructor is a special method invoked when an object of the class is created (via new):

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args) {
        Person person = new Person("John", 20);
        System.out.println("The name of the person is " + person.name);
    }
}

If a class has no constructor, the Java compiler automatically creates a default constructor. Take the same class with the constructor deleted and new Person() called instead — it still compiles, because the compiler supplies the no-argument constructor. name is never assigned, so the println would print null.

public class Person {
    private String name;
    private int age;

    public static void main(String[] args) {
        Person person = new Person();
        System.out.println("The name of the person is " + person.name);
    }
}

Notes on constructors:

  • Constructors are invoked implicitly when objects are instantiated.
  • The constructor’s name MUST be the same as the class.
  • A Java constructor must not have a return type.
  • If a class does not have a constructor, the compiler creates a default constructor. This happens at compile time, not at run time: the compiler emits it into the class file.
  • A constructor can be overloaded but can not be overridden.

Access modifiers

Access modifiers set the accessibility (visibility) of classes, interfaces, properties, methods, constructors, and data members:

Modifier Accessible from
private Only within the declaring class
public Anywhere
protected Same package, plus subclasses (see java-inheritance)
(default, no keyword) Only within the same package

The same BankAccount under three of the four:

private — the field cannot be touched from outside the class, so this does not compile:

public class BankAccount {
    private double balance;
    private String accountNumber;
    private String accountHolder;
    private double interestRate;
}

public class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount();
        account.balance = 1000.0;   // compile error
    }
}

java: balance has private access in Week02.OOP.AccessModifers.BankAccount

public — change balance to public double balance; and the assignment that would not compile above is now legal. Add System.out.println("Balance: " + account.balance); to Main and it prints Balance: 1000.0.

default (no keyword) — drop the modifier entirely (double balance;) and, because Main is in the same package, it also compiles and prints Balance: 1000.0. The difference from public only shows up across a package boundary.

protected is homework: read DigitalOcean’s Java access modifiers tutorial. It is accessible within the same package as well as from subclasses. The subclass clause is what makes protected wider than default access, because it reaches subclasses in other packages too.

Getters and setters

Getter and setter methods provide controlled access to an object’s private fields, keeping its internal representation hidden from the outside world:

  • Getters (accessors) retrieve the value of a private field from outside the class.
  • Setters (mutators) set/update the value of a private field from outside the class.
public class BankAccount {
    private double balance;
    private String accountNumber;

    public BankAccount(String accountNumber) {
        this.accountNumber = accountNumber;
    }

    public double getBalance() { return balance; }
    public void setBalance(double balance) { this.balance = balance; }
    public String getAccountNumber() { return accountNumber; }
}

public class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount("111000");
        account.setBalance(10000);
        System.out.println("Balance: " + account.getBalance());
        System.out.println("Account number: " + account.getAccountNumber());
    }
}

The example is asymmetric: balance gets both a getter and a setter, accountNumber gets only a getter. Whether a field is writable from outside is a per-field design decision, not something you owe every field.

The static keyword

static is a non-access modifier for methods and attributes:

  • Static methods/attributes can be accessed without creating an object of the class.
  • Useful in memory management; can be applied to variables, methods, blocks, and nested classes.
  • In procedural programming the same keyword means something different: it marks a variable or function whose scope is limited to the file it is declared in.

Static variables (class variables) are shared among all instances of a class — useful for constants and shared properties:

class BankAccount {
    public static int totalAccounts = 0;

    private double balance;
    private String accountNumber;
    private String accountHolder;

    public BankAccount(double balance, String accountNumber, String accountHolder) {
        this.balance = balance;
        this.accountNumber = accountNumber;
        this.accountHolder = accountHolder;
    }

    public String getAccountNumber() { return accountNumber; }
    public double getBalance() { return balance; }
    public String getAccountHolder() { return accountHolder; }
}

Static methods can be called without creating an instance, but cannot access non-static (instance) variables or methods directly:

class Bank {
    static double interestRate = 5.0;

    static double calculateInterest(double balance, int years) {
        return (balance * interestRate * years) / 100;
    }
}

class BankAccount {
    private String accountHolder;
    private double balance;

    BankAccount(String name, double balance) {
        this.accountHolder = name;
        this.balance = balance;
    }

    void showInterest(int years) {
        double interest = Bank.calculateInterest(balance, years);
        System.out.println(accountHolder + " earns $" + interest + " in " + years + " years.");
    }
}

The call site is the point of the example: it reads Bank.calculateInterest(...) — on the class, not on an instance — and because calculateInterest is static it cannot reach any account’s balance itself, so the balance has to be handed to it as an argument. The static field interestRate, by contrast, it can read directly, because that field belongs to the class too.

Class invariants

A class invariant specifies a condition (or set of conditions) that should always be true throughout the life of an object — used to ensure a system remains in a valid state. Put more precisely, it is a constraint that must hold at every stable point in time during the life of an object. A class invariant:

  1. Must be established after the class constructor.
  2. May be assumed as a precondition of each method (excluding the constructor).
  3. Must be established after each method call.
class Counter {
    private int count;
    public Counter() { count = 0; }
    public void increment() { count = count + 1; }
}
// Invariant: count >= 0

Trace the three rules against Counter: the constructor sets count = 0, which establishes count >= 0; increment may assume count >= 0 on entry; and since it only ever adds 1, count >= 0 still holds on exit. Nothing else can reach count, because it is private — which is what makes the invariant enforceable at all rather than merely hoped for.

Invariants complement preconditions (what must be true before a method executes) and postconditions (what must be true after) — together these define a contract for how a method or function should behave. Pre/postconditions themselves are in java-specification and java-hoare-logic; see also week8-tutorial-class-invariants.

Protecting invariants

The Counter example does not show how an invariant can be broken from outside. Guarding against that is what makes the definition enforceable rather than merely stated; see also week8-tutorial-class-invariants and the defensive-programming material in java-specification.

A specification can claim an invariant while the implementation still allows it to be broken. Two common leaks:

  1. Public fields — a directly-mutable field lets any caller bypass the class entirely and violate the invariant. Fix: make the field private.
  2. Returning an internal reference — a getter that returns its internal mutable collection/object directly hands the caller a way to mutate it from outside, bypassing any checks the class’s own methods perform. Fix: return a defensive copy:
private List<String> files;

public List<String> getFiles() {
    return new ArrayList<>(files); // copy, not the internal reference
}

Preserving the invariant may also require adding preconditions to methods that could otherwise violate it (e.g. rejecting an addition that wouldn’t satisfy the invariant), or, when a method is likely to be called by code outside your control, defensively throwing an exception (e.g. IllegalArgumentException/IllegalStateException) rather than relying purely on the precondition contract (see java-specification — Defensive programming).

Method signatures

A method signature is a method’s unique identifier: its name plus its parameter types. The return type and the parameter names do not count towards the signature, and a signature MUST be unique within a class:

public void print() { ... }              // signature: print()
public void print(int parameter) { ... } // signature: print(int)

Worked question — is this allowed?

public class Action {
    public Boot fish(int strength, int rodLength) { ... }
    public Fish fish(int strength, int polLength) { ... }
}

No. Both methods have the signature fish(int, int). The differing return types (Boot vs Fish) and the differing parameter names (rodLength vs polLength) are exactly the two things a signature ignores, so the class will not compile. This same rule is what makes overriding work in java-inheritance: an override must repeat the superclass method’s signature exactly, or it is a new overload rather than an override.

Java Events

Introduced in 2026-05-14-lambdas-streams-and-events (Guest lecture, Week 11). Not examinable — see the note at the top of that lecture.

Event-driven programming

A common design pattern for how to control the flow of your program: basically a different way to glue together your various chunks of code.

You subscribe chunks of your code (often lambdas, see java-lambdas-and-streams) to a listener for specific events emanating from specific sources; when the event is triggered, the subscribed code is activated. For example, clicking a button spawns a click event, which is then passed to anything subscribed to / listening for the click of that button.

The payoff is that the system becomes more discrete: each chunk does not need to know about other irrelevant details. That is low coupling, see java-cohesion-and-coupling.

It is incredibly common in two places:

  • GUI programming — if you have done any GUI work on the web or with a desktop toolkit you have already used events.
  • Network programming — Node.js, the JavaScript server runtime, is event-driven under the hood.

The event loop

The event system itself is generally run on a separate thread, or via a task-prioritisation (macro vs micro) architecture, and what it runs is an event loop:

An event loop is a program that takes an event from a queue of events, and alerts all subscribed listeners that this event has occurred, dispatching the event information to them.

Mostly you hook into one rather than writing it: many applications ship an event loop for you to use as a developer, and some languages build one into the language itself — JavaScript is the iconic example. In Java, Swing and JavaFX both come with their own event systems you can hook into.

Building a toy event system

Events are easy to pick up and use. They are often the first design pattern people meet, at high school, without realising it, when they wire up buttons on a basic website. Using them does not show the internals. The two things you would not naturally pick up:

  1. an implementation of a basic, naive event system, so you can vaguely understand how they work under the hood;
  2. a variation of the CSSE2002 game engine with a basic event system integrated, to show how that simplifies existing code on the developer’s end.

The API

A basic event system needs only lambdas and 2 classes:

SimpleEvent (String type, String data):  getType():String, getData():String

EventSystem
    addListener(String type, Consumer<SimpleEvent> action): action
    removeListener(Consumer<SimpleEvent> action)
    addEvent(SimpleEvent event): void
    tick(): void

SimpleEvent is just a named bundle of data — a type string that says what happened and a data string carrying the payload, with a getter for each. The signatures give EventSystem no fields. Reading the four method names against the definition of an event loop above, it needs two pieces of state: a queue of events not yet dispatched, and a map from event type to the listeners subscribed to it.

Two details worth reading off the signatures:

  • addListener returns the action back to you. The natural reading is that it hands you a handle to unsubscribe with later: if you passed the listener in as an inline lambda you have no other reference to it, and removeListener needs exactly that reference.
  • removeListener is the one method with no return type given. Every other method has one (:String, : action, : void), so treat its return as unspecified rather than assuming void.

Figure 73: How the four EventSystem methods fit together: a queue of pending events, a map from event type to the listeners subscribed to it, and the numbered steps tick() takes to dispatch one event.

On the same reading, tick() is what actually drives the loop: it takes an event off the queue, looks up event.getType() in the listener map, and calls each subscribed Consumer<SimpleEvent> with the event itself as the argument. So nothing happens between ticks, and queuing an event only schedules it.

NoteSimpleEvent written out

Written out as a class, the SimpleEvent signature is:

class SimpleEvent {
    private String type;
    private String data;

    public SimpleEvent(String type, String data) {
        this.type = type;
        this.data = data;
    }

    public String getType() { return type; }
    public String getData() { return data; }
}

Motivating example: the CSSE2002 game engine

The engine you used in the assignments is very linear: you called .tick(), passed in the various states, and then the parent tiles and managers would tick their children, passing the state down accordingly.

That works, but it tightly links everything around that tick() method as the mechanism for state being passed between the various parts of the program. An event system drastically cuts down on this connective tissue code: the code that exists only to shuttle state through layers that do not otherwise care about it. The saving comes from letting far-apart parts talk through the event system rather than through their common ancestor.

Figure 74: Why the game engine is the motivating example. Without an event system, parent tiles and managers tick their children and pass state down, so the only route from Tile A to Tile D runs up through the Engine and back down. With one, A and D talk through the EventSystem and the managers in between carry nothing.

Java Exceptions

Introduced in 2026-03-19-exceptions (Lecture, Week 4, Part 1). Traced in depth in week5-tutorial-exceptions.

What is an exception?

An unexpected event that occurs during program execution, e.g.:

System.out.println(5 / 0); // Infinity??

No — integer division by zero causes a java.lang.ArithmeticException: / by zero. Infinity is the tempting wrong answer: it is what floating-point division gives, not integer division.

Common causes:

  • invalid user input
  • loss of network connection
  • physical limitations (out of disk memory)
  • code errors
  • opening an unavailable file

When an exception occurs within a method it creates an object — the exception object — which contains information about the exception. Effective Java (2017), Item 75, says to include failure-capture information in detail messages: that object is where the diagnostic information has to live.

We can catch the exception to handle it, and the catch block is where the program is put back into a usable state:

try {
    System.out.println(5 / 0);
}  catch (ArithmeticException e) {
    System.out.println(e); // print out error message
    //do something to recover
}

Exception hierarchy

Figure 75: The exception hierarchy. Throwable is the root; Error and Exception sit beneath it; RuntimeException (unchecked) and IOException (checked) sit beneath Exception. Each connector joins the subclasses and points up to their parent. Which branch a class is on is what decides whether the compiler forces you to handle it, so this one picture settles the checked/unchecked question.

RuntimeException — unchecked

A runtime exception happens due to a programming error. Also known as unchecked exceptions: the compiler does not force you to handle them.

Cause Exception
Improper use of an API IllegalArgumentException
Null pointer access NullPointerException
Out-of-bounds array access ArrayIndexOutOfBoundsException
Dividing a number by 0 ArithmeticException

IOException — checked

Also known as a checked exception: it is checked by the compiler at compile time, and the programmer is prompted to handle it.

Cause Exception
Trying to open a file that doesn’t exist FileNotFoundException
Trying to read past the end of a file EOFException
A connection attempt to a remote host fails ConnectException

Java exception handling

There are three mechanisms: the try…catch block, the throw and throws keywords, and the finally block.

try … catch

Place the code that might generate an exception inside the try block. Every try block is followed by a catch block.

int result;
try {
    result = 5 / 0;
    …
} catch (ArithmeticException e) {
    System.out.println(e);      // print out error message
    result = Integer.MAX_VALUE; // Assign a default or fallback value
}
  1. When an exception occurs, the rest of the code inside the try block is skipped.
  2. The catch block catches the exception and the statements inside the catch block are executed.
  3. If none of the statements in the try block generates an exception, the catch block is skipped.

Figure 76: The two paths through a try/catch/finally, and the fact that both of them end up in finally. This is the three numbered rules together with the finally rule, drawn as one picture: the exceptional path abandons the remaining statements of the try and enters catch, the normal path skips catch entirely, and neither can skip finally.

throw

The throw keyword is used to explicitly throw a single exception. Two examples:

public class Main {
    public static void main(String[] args) {
        divideByZero();
    }
    public static void divideByZero() {
        // throw an exception
        throw new ArithmeticException("Trying to divide by 0");
    }
}
public class Main {
    public static void main(String[] args) {
        checkEntry(17);
    }

    public static void checkEntry(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("Access denied ");
        }
        else {
            System.out.println("Access granted ");
        }
    }
}

throw is used to manually trigger an error when your program detects something invalid, so it doesn’t continue in a bad state. That is the point of the whole keyword, and it is also the bridge to java-specification: throwing is how a method refuses input that breaks its precondition instead of limping on.

throws

The throws keyword declares the type of exceptions that might occur within the method, and it is used in the method declaration. The caller is then the one prompted to handle it:

public class ThrowsEx {
    public static void main(String[] args) {
        try {
            findFile();
        } catch (FileNotFoundException e) {
            System.out.println(e);
        }
    }
    public static void findFile() throws FileNotFoundException {
        // code that may generate FileNotFoundException
        File newFile = new File("file.txt");
        FileInputStream stream = new FileInputStream(newFile);
    }
}

throw and throws are not two spellings of one thing: throw (statement, inside a body) raises an exception; throws (clause, in a signature) declares that one can escape. Only checked exceptions have to be declared — that is exactly what “checked by the compiler” buys you.

finally

  • The finally block is executed regardless of whether an exception is thrown.
  • The finally block is optional.
try {
    //code
}
catch (ExceptionType1 e1) {
    // catch block
}
finally {
    // finally block always executes
}

Exercise — what will the following print?

try{
    System.out.println("Good Morning");
    throw  new FileNotFoundException();
    System.out.println("the earth says");
}catch (Exception e){
    System.out.println("hello");
}finally {
    System.out.println("world");
}

Answer:

Good Morning
hello
world

Working through it against the rules above: "Good Morning" prints; the throw immediately abandons the rest of the try, so "the earth says" never prints; the catch parameter is Exception, and FileNotFoundException is an Exception, so this catch matches and "hello" prints; finally always runs, so "world" prints last.

As written this snippet would not actually compile. System.out.println("the earth says"); sits directly after an unconditional throw in the same block, and Java rejects that at compile time as an unreachable statement. Read it as a tracing exercise about the order of the three rules, not as something to paste into a file.

Custom exceptions

Define your own by extending Exception (or a subclass of it), then declare it with throws and raise it with throw:

public class MyCustomException extends Exception {
...

}

int myFunction() throws MyCustomException {
throw new MyCustomException();
}

Worked example — ItemNotFoundException

The exception class gives a no-argument constructor with a fixed message and a second constructor taking a custom one, both delegating to super(...) — the Throwable message is the failure-capture information from Item 75:

public class ItemNotFoundException extends Exception{
    public ItemNotFoundException(){
        super("Item not found");
    }
    // Constructor that accepts a custom message
    public ItemNotFoundException(String message) {
        super(message);
    }
}

The class that uses it declares throws on the searching method and throws when the loop falls through without a match:

public class Store {
    private List<String> items;
    public Store() {
        items = new ArrayList<>();
        items.add("apple");
        items.add("banana");
        items.add("orange");
    }
    public String findItem(String itemName) throws ItemNotFoundException {
        for (String item : items) {
            if (item.equals(itemName)) {
                return item;
            }
        }
        throw new ItemNotFoundException("Item '" + itemName + "' not found in the list.");
    }

    public static void main(String[] args) {
        Store store = new Store();
        try {
            String item = store.findItem("grape");
            System.out.println("Found item: " + item);
        } catch (ItemNotFoundException e) {
            System.err.println(e.getMessage());
        }
    }
}

findItem("grape") misses, so the try is abandoned at the call — "Found item: …" never prints — and the catch reports Item 'grape' not found in the list. on System.err.

Java Generics

Introduced in 2026-04-30-generics-in-java (Lecture, Week 9). Practised again in week12-lab-generics.

Generics let reference types (Integer, String, … and user-defined types) be parameters when defining classes, interfaces and methods. There are two separate motivations for that, and they are worth keeping apart.

Why generics? (1) Type safety

Prior to Java 1.5, collection classes could hold any type of object — ArrayList.add was declared

public boolean add(Object o) {
    // code to implement add method.
}

so anything could go in, and an explicit cast was needed on the way out (see java-casting):

List list = new ArrayList();
list.add("Hello");
list.add(123);           // allowed
list.add(new Date());    // allowed

String str = (String) list.get(0);    // OK
Integer num = (Integer) list.get(1);  // OK
Date date = (Date) list.get(2);       // OK

The trap: Integer num = (Integer) list.get(2); compiles, because the compiler only knows get returns Object. It fails at run time with a ClassCastException, because slot 2 holds a Date. Nothing about the list stops a String being mixed into a collection that was only ever meant to hold Cars, because add accepts any Object.

Declaring the element type fixes both problems at once:

List<String> list = new ArrayList<>();  // <> is the diamond operator
list.add("Hello");
list.add(123);                // compile-time error
String str = list.get(0);     // no cast needed
List<Car> carList = new ArrayList<Car>();
Car c = carList.get(0);       // the compiler already knows it is a Car

This is type safety: type-related errors are caught and prevented early, at compile time, instead of surfacing as unintended bugs at run time.

List<Object> list = new ArrayList<>();
list.add("Hello");
list.add(123);

Object object1 = list.get(0);
Object object2 = list.get(1);

It compiles, and it accepts both. But parameterising by Object buys nothing, because everything is an Object. Elements come back typed Object, so you are casting again, and add accepts anything again. Generics only pay off when the parameter is a specific type.

Why generics? (2) One class instead of one class per type

The second motivation is duplication, not safety. A class that prints an Integer:

public class PrintInt {
    Integer i;
    PrintInt(Integer i) { this.i = i; }
    public void print() { System.out.println(i); }
}

Wanting the same thing for Double, Float and String means writing PrintDouble, PrintFloat and PrintString — four classes with identical bodies and one word changed. Generics collapse them into one class that still preserves type safety.

Generic classes

A generic class parameterises a type across its whole body:

public class Print<T> {
    T i;
    Print(T i) { this.i = i; }
    public void print() { System.out.println(i); }
}

Print<Integer> print  = new Print<>(1);
Print<Double>  print2 = new Print<>(1.1);
Print<String>  print3 = new Print<>("1.1");

By convention, type parameters are single letters: T (Type), E (Element — used extensively by the Java Collections Framework, see java-collections-framework), K (Key), V (Value), N (Number), and S/U/V… for a 2nd/3rd/4th type.

Generic methods

A single method can be made generic, independently of whether its enclosing class is. The type parameter is declared between the modifiers and the return type:

public <T> void genericsMethod(T data) {
    // do something with data
}

public <T> T genericsMethod(T data) {
    // do something with data here
    return data;                 // returning any T-type value
}

Multiple type parameters can be declared together, and the return type can be a third one:

public <T, S, R> R genericMethod(T value1, S value2) {
    return null;
}

String result = genericMethod(42, 3.14);

Type inference

A Printer whose print method is generic, in place of a fixed-type one:

public class Printer {
    public <T> void print(T data) {
        System.out.println("Lets shout " + data + "!!!");
    }
}

Printer printer = new Printer();
printer.print(124);                  // T inferred as Integer
printer.print("I love CSSE2002");    // T inferred as String

The Java compiler can automatically determine the type of T based on the type of the argument you pass to the method. This is known as type inference.

public class Printer<T> {
    public void print(T data) {
        System.out.println("Lets shout " + data + "!!!");
    }

    public static void main(String[] args) {
        Printer<String> printer = new Printer<>();
        printer.print("data");
        printer.print(123);
    }
}

A class type parameter is fixed once, when the object is created. new Printer<>() assigned to Printer<String> pins T = String for the life of that object, so printer.print(123) is a compile-time error. A method type parameter is inferred afresh at every call, which is why the generic-method version above accepted an Integer and a String through the same object. Choose the class parameter when one object should work with one type throughout; choose the method parameter when each call is independent.

Bounded generics

A type parameter can normally accept any reference type. Bounded generics restrict it to a specific type or its subtypes, using extends. The form is <T extends X>, and it means T can only accept data that are subtypes of X. Restricting the Printer to numbers:

public class Printer {
    public <T extends Number> void print(T data) {
        System.out.println("Lets shout " + data + "!!!");
    }
}

printer.print(123);      // OK, Integer is a Number
printer.print(123.2);    // OK, Double is a Number
printer.print("123");    // compile-time error - String is not a Number

Despite the keyword, extends here also covers implementing an interface.

Bounds through wildcards

Generic-type bounding restricts what may be substituted for the type parameter. Wildcards (?) do this at the use site — in a method’s parameter list — rather than where a generic class or method is declared. Three forms:

Form Name
List<?> unbounded wildcard
? extends T upper bound wildcard
? super T lower bound wildcard

Figure 77: The two bounded wildcards drawn on the Number hierarchy. ? extends Number admits Number and everything below it — you may read elements as Number, but add is refused; ? super Integer admits Integer and everything above it — you may add an Integer, and List<Double> is refused. Object is on top because the addNumbers example passes a List<Object>.

Unbounded wildcard: List<?>

List<?> means “a list of some unknown type”. Java does not know whether it is actually a List<String>, a List<Integer> or a List<Product> — therefore it prevents the caller from writing to the list:

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        addSomething(numbers);
    }

    public static void addSomething(List<?> list) {
        list.add("Hello");   // error
    }
}

The compiler has to refuse: if Java allowed "Hello" to be added, the List<Integer> would now contain a String, breaking type safety.

Choosing between <T> and <?> for a read-only method:

public <T> void printList(List<T> toPrint) {
    for (int i = 0; i < toPrint.size(); i++) {
        System.out.println(toPrint.get(i));
    }
}
public void printList(List<?> toPrint) {
    for (int i = 0; i < toPrint.size(); i++) {
        System.out.println(toPrint.get(i));
    }
}

Use <T> when you need to work with the type. Use <?> when you only need to read values.

Wildcards are usually bounded (<? extends T>, <? super T>) to reduce flexibility and improve safety.

Upper bounded wildcard: ? extends T

Represents T or any subclass of T. Used mainly to read data from a structure — you cannot safely add to it, because the exact subtype is unknown:

List<? extends Number> nums = new ArrayList<Integer>();

Number n = nums.get(0);  // OK: read as Number
nums.add(10);            // compile-time error

The reason this form is needed at all is invariance. Write a sum over a List<Number>:

public static double sum(List<Number> list) {
    double sum = 0;
    for (Number n : list) {
        sum += n.doubleValue();
    }
    return sum;
}

List<Double> numbers = new ArrayList<>();
numbers.add(1.1);
sum(numbers);   // does not compile

In standard inheritance Number n = 5.0; is fine, because Double is a subclass of Number. But generics in Java are invariant: even though Double is a subclass of Number, List<Double> is not a subclass of List<Number>. (Effective Java, Item 31: parameterized types are invariant; List<Type1> is neither a subtype nor a supertype of List<Type2>.) Widening the parameter with an upper bound is what makes the method accept both:

public static double sum(List<? extends Number> list) {
    double sum = 0;
    for (Number n : list) {
        sum += n.doubleValue();
    }
    return sum;
}

…and the price is that the method still cannot safely write, because it does not know whether the actual list is a List<Double>, a List<Integer>, or something else.

Lower bounded wildcard: ? super T

Represents T or any of its superclasses. Used when you want to perform write operations on a generic collection but keep flexibility in which collections are accepted:

public class Main {
    public static void addNumbers(List<? super Integer> list) {
        list.add(1);   // Allowed: Integer is within bounds
        list.add(2);   // Allowed: Integer is within bounds
    }

    public static void main(String[] args) {
        List<Number> numbers = new ArrayList<>();
        addNumbers(numbers);   // fine: Number is a superclass of Integer

        List<Object> objects = new ArrayList<>();
        addNumbers(objects);   // fine: Object is also a superclass of Integer

        List<Double> doubles = new ArrayList<>();
        addNumbers(doubles);   // compilation error
    }
}

Type erasure

Generics provide type checking at compile time only. Java implements them by type erasure, which removes all type parameters during compilation, replacing each with

  • its upper bound (e.g. Number, for <T extends Number>), or
  • Object, if unbounded.

As a result, generic type information is not available at run time.

Figure 78: Type erasure as a pipeline: the compiler checks the source against the type parameters, erases each parameter to its bound (Object if unbounded), and inserts the casts the erased code needs — so the cast you were told you did not have to write still happens, just not by you. The top row is the compile-time source and what runs after javac, with the inserted cast in the red rectangle. The bottom row is what an unbounded and a bounded parameter each erase to.

Spelled out for a bounded parameter — the compiler replaces T with the extended class:

// Source
class SomeClass<T extends Number> {
    private T t;
    public void add(T t) { this.t = t; }
    public T get() { return t; }
}

// After type erasure, the compiler generates
class SomeClass {
    private Number t;
    public void add(Number t) { this.t = t; }
    public Number get() { return t; }
}

and for an unbounded one, T becomes Object (private Object t;, public void add(Object t), public Object get()).

Practical example: a bookshop

Imagine you are developing a system for a bookshop that sells books across various genres: Fiction, Action, and Fantasy. Books are in bookshelves. Your job is to design the system in a way that allows the shop to store books of these different genres and retrieve them when needed.

The genres are subclasses of an abstract Book:

public abstract class Book {
    private String title;
    private String author;

    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }
    public String getTitle()  { return title; }
    public String getAuthor() { return author; }
    public abstract String getGenre();
}

public class Fiction extends Book {
    public Fiction(String title, String author) { super(title, author); }
    @Override
    public String getGenre() { return "Fiction"; }
}
// Action is identical, returning "Action"

Figure 79: The three shelf designs, and why only the third is both reusable and type safe. One shelf of Book is reusable but needs a cast; a separate shelf class per genre gives better type safety but creates duplicated code; class BookShelf<T extends Book> gets both. The stacked outlines behind FictionShelf stand for the same class written out again for the other genres.

Without generics

One BookShelf storing the abstract Book type loses the genre on retrieval:

public class BookShelf {
    private List<Book> inventory = new ArrayList<>();

    public void addItem(Book item) { inventory.add(item); }
    public Book getItem(int index) { return inventory.get(index); }

    public void displayBooks() {
        for (Book book : inventory) {
            System.out.println(book.getTitle() + " (" + book.getGenre() + ")");
        }
    }
}

The failure, worked through. The commented-out line is the one that breaks:

BookShelf shelf = new BookShelf();
shelf.addItem(new Fiction("The Hobbit", "J.R.R. Tolkien"));
shelf.addItem(new Action("Die Hard", "Roderick Thorp"));
shelf.addItem(new Fiction("Harry Potter", "J.K. Rowling"));

Book b = shelf.getItem(0);                       // returns Book

Fiction f  = (Fiction) shelf.getItem(0);         // fine
// Fiction f2 = (Fiction) shelf.getItem(1);      // breaks: index 1 is an
//                                               // Action -> ClassCastException
Action f2  = (Action) shelf.getItem(1);          // the caller has to know

getItem() returns only Book, so retrieving a genre needs a cast, and a wrong cast is a ClassCastException — not type safe.

Writing separate FictionShelf/ActionShelf classes instead does give better type safety, but every shelf is the same class copied out again:

public class FictionShelf {
    private List<Fiction> inventory = new ArrayList<>();
    public void addItem(Fiction book) { inventory.add(book); }
    public Fiction getItem(int index) { return inventory.get(index); }
    public void displayBooks() { for (Book book : inventory) { /* ... */ } }
}
// class ActionShelf { ...the same again with Action... }

With generics

A single generic BookShelf<T extends Book> gives type safety and reuse from one class. The bound matters twice over: it is what lets displayBooks call book.getGenre() (the compiler knows every T is at least a Book), and what stops a BookShelf<String> ever being created.

public class BookShelf<T extends Book> {
    private List<T> inventory = new ArrayList<>();

    public void addItem(T item) { inventory.add(item); }
    public T getItem(int index) { return inventory.get(index); }

    public void displayBooks() {
        for (T book : inventory) {
            System.out.println(book + "(" + book.getGenre() + ")");
        }
    }
}

BookShelf<Fiction> fictionShelf = new BookShelf<>();
BookShelf<Action>  actionShelf  = new BookShelf<>();

fictionShelf.addItem(new Fiction("The Hobbit", "J.R.R. Tolkien"));
fictionShelf.addItem(new Fiction("Harry Potter", "J.K. Rowling"));
actionShelf.addItem(new Action("Die Hard", "Roderick Thorp"));

fictionShelf.displayBooks();   // getItem() here returns Fiction, no cast
actionShelf.displayBooks();

Java Hoare Logic

Introduced in 2026-05-21-correct-programming (Lecture, Week 12). Formalises reasoning about java-specification’s preconditions/postconditions.

What does it mean for a program to be correct?

A correct program satisfies its specification.

Correctness is only meaningful relative to a specification — asking “is this program correct?” without one is unanswerable:

public int indexOf(int[] numbers, int number) {
    for (int i = 0; i < numbers.length; i++) {
        if (numbers[i] == number) {
            return i;
        }
    }
    return -1;
}
  • With no spec at all: maybe correct, maybe not — we can’t say without knowing what it’s meant to do.
  • Spec’d as /** Returns how many times number occurs in numbers. */: incorrect — counter-example indexOf({1, 1, 1, 1}, 1) == 0, but a correct implementation of that spec should return 4.
  • Spec’d as /** Returns the index of number within numbers, if number is in numbers. */: correct, but the spec is underspecified — it says nothing about what happens when number isn’t in numbers.

A specification restricts the space of acceptable implementations: think of all possible input/output pairs as arrows crossing an Implementation/Specification boundary — an implementation is correct exactly when every arrow it draws stays within the region the specification permits. A @requires/@ensures Javadoc comment (see java-specification) states the precondition and postcondition that bound this region.

Hoare triples

Preconditions and postconditions aren’t just for whole methods — every block of code has them. We write this as a Hoare triple:

\[\{P\}\ S\ \{Q\}\]

meaning: if precondition \(P\) holds before statement(s) \(S\) run, postcondition \(Q\) holds afterwards. E.g.:

// {true}
if (x > y) {
    max = x;
} else {
    max = y;
}
// {max >= x && max >= y}

Deriving preconditions by propagating backward

Given a method’s postcondition, we can work out its precondition (or verify a block of code) by propagating the postcondition backward through each statement, substituting as we go.

Straight-line code

/**
 * @requires numbers != null && 2 < numbers.length && numbers[2] == number
 * @ensures numbers[\result] == number
 */
public int indexOf(int[] numbers, int number) {
    // {numbers[0 - 10 + 12] == number}
    int result = 0;
    // {numbers[result - 10 + 12] == number}
    result = result + 12;
    // {numbers[result - 10] == number}
    result = result - 10;
    // {numbers[result] == number}
    return result;
    // {numbers[\result] == number}
}

Each line’s precondition is obtained by substituting the assigned expression into the next line’s already-derived precondition, working from the @ensures postcondition backward to the top of the method — the resulting @requires is whatever’s left once you reach the very first line.

The direction is the part that trips people up: the listing reads top-to-bottom but is derived bottom-to-top, and each rung of the derivation is a single textual substitution.

Figure 80: The same derivation as the listing above, laid out so the direction of the reasoning is visible: the @ensures at the bottom is given, each statement rewrites the assertion below it by replacing the assigned variable with the expression assigned to it, and whatever is left at the top is the @requires. The assertions are in green; they are // comments in the listing.

Through if/else

Each branch is handled separately, and the two derived preconditions are combined into a single condition depending on which branch executes:

/**
 * @requires numbers != null && 12 < numbers.length
 *               && numbers[12] == number && number % 2 == 0
 * @ensures numbers[\result] == number
 */
public int indexOf(int[] numbers, int number) {
    // {number % 2 == 0 ==> numbers[0 + 12] == number
    //  && number % 2 != 0 ==> numbers[0 - 10] == number}
    int result = 0;
    if (number % 2 == 0) {
        // {numbers[result + 12] == number}
        result = result + 12;
    } else {
        // {numbers[result - 10] == number}
        result = result - 10;
    }
    // {numbers[result] == number}
    return result;
}

Both branches must reach the same postcondition {numbers[result] == number}, so the derivation forks there, runs up each branch independently, and only rejoins once each branch’s precondition has been guarded by the condition that selects it:

Figure 81: The if/else derivation above drawn as a fork and join. Reading upward: one shared postcondition, two independent branch derivations, then a single combined condition in which each branch’s requirement is guarded by the test that reaches it, and finally one more substitution through int result = 0;. The combined assertion in the middle is the top condition one substitution earlier, a step the listing skips over.

Compare the top of Figure 81 with the @requires the method actually declares. The derived condition covers both branches; the declared one, numbers != null && 12 < numbers.length && numbers[12] == number && number % 2 == 0, pins number to the even case. That is legal — a stronger precondition than the derived one is always safe, because it still implies it (with number % 2 == 0 fixed, the second disjunct is vacuously true) — it just means the method promises less than the code could deliver. Deriving gives you the weakest precondition; what you write in the Javadoc may be anything that implies it.

Proving a block correct

The same backward-propagation technique proves an arbitrary block of code satisfies a given Hoare triple — substitute back through each branch/statement and confirm the starting precondition (true, in these examples) is actually implied:

// {true}
if (x > y) {
    // {x > y} ==> {x >= x && x >= y}
    max = x;
    // {max >= x && max >= y}
} else {
    // {y >= x} ==> {y >= x && y >= y}
    max = y;
    // {max >= x && max >= y}
}
// {max >= x && max >= y}

A three-statement swap works the same way, substituting each assignment’s right-hand side backward through \old(...) references:

// {true}
// {y == \old(y) && x == \old(x)}
int tmp = x;
// {y == \old(y) && tmp == \old(x)}
x = y;
// {x == \old(y) && tmp == \old(x)}
y = tmp;
// {x == \old(y) && y == \old(x)}

A trickier variant swaps x/y using only arithmetic (no temporary variable), which still propagates the same way:

// {true}
// {y == \old(y) && x == \old(x)}
// {y - (y - x) + (y - x) == \old(y) && y - (y - x) == \old(x)}
x = y - x;
// {y - x + x == \old(y) && y - x == \old(x)}
y = y - x;
// {y + x == \old(y) && y == \old(x)}
x = y + x;
// {x == \old(y) && y == \old(x)}

(A similar swap is possible using bitwise XOR instead of subtraction, exploiting \(a \oplus b = b \oplus a\), \((a \oplus b) \oplus c = a \oplus (b \oplus c)\), \(a \oplus 0 = a\), \(a \oplus a = 0\).)

Writing the triple down: \result and \old(...)

A Hoare triple written in Java lives in a Javadoc comment (see java-specification): \(P\) goes in the precondition tag, \(Q\) in the postcondition tag, and \(S\) is the method body. Two pieces of vocabulary let a postcondition say things a plain Java boolean expression cannot.

  • \result names the value the method returns. It is the established way to refer to a return value inside a postcondition.
  • \old(e) names the value the expression e had before the call. It is defined in java-specification and is used again in the Week 12 practical. Without it the swap derivations above could not be stated at all: x == y && y == x says nothing, whereas x == \old(y) && y == \old(x) is exactly the swap.
NoteThe contract tags are spelled two ways in this course

The tags are @requires / @ensures here and in the tag table in java-specification. The Week 12 practical sheet (week12-lab-generics) writes @require / @ensure, with no trailing s, and so do the SOLID contracts. Neither form is canonical. Use whichever form the sheet in front of you uses.

A worked contract from the Week 12 practical

The practical’s transferStudents (Task 4) is the fullest contract in the Week 12 material, and it uses both pieces of vocabulary. Its @ensure writes bus.getCurrentCount without the parentheses:

/**
 * Transfer students to the new bus.
 *
 * @param students Bus only containing Concession fare riders.
 * @param bus      Bus to which students will transfer.
 * @require students != null
 *          && bus.getCapacity() >= students.getCurrentCount()
 * @ensure  students.getCurrentCount() == 0
 *          && bus.getCurrentCount >= \old(students).getCurrentCount()
 *          && bus contains all passengers from \old(students)
 */
public static void transferStudents(Bus<Concession> students,
        Bus<? super Concession> bus) { ... }

The method returns void, so there is no \result to talk about; everything the postcondition has to say is about how two objects’ states changed, which is what makes \old(...) indispensable here. students.getCurrentCount() == 0 is a fact about the state after; \old(students).getCurrentCount() reaches back to the state before, so the middle clause can hold the target bus’s final count up against the number of passengers the source bus had before the call.

Figure 82: The Week 12 practical’s transferStudents contract as a before/after picture, on a source bus of capacity 4 carrying three passengers and a target bus of capacity 6 already carrying two. Each bus is an array with its name to the left. The contract text is in green and the annotation in magenta.

Two things about this contract as written.

The postcondition mixes Java and English in the same tag. students.getCurrentCount() == 0 is a boolean expression; bus contains all passengers from \old(students) is a sentence. The course convention is that conditions are written in Java boolean syntax, not mathematical notation, but the only queries Bus exposes are getCurrentCount() and getCapacity() (its other two methods, passengerOn and passengerOff, both mutate), so there is no expression in the API that can say “contains”. The contract falls back to prose rather than inventing one, and the same happens in Task 3, whose whole postcondition is @ensure \result contains trainee and all trainers.

The precondition is weaker than the postcondition needs. bus.getCapacity() >= students.getCurrentCount() compares the target’s total capacity against the number of students, not its free space. Bus.passengerOn (Task 0) silently does nothing when the bus is full:

public void passengerOn(T passenger) {
    if (currentCount < capacity) {
        passengers[currentCount++] = passenger;
    }
}

so a bus of capacity 6 already carrying 4, given a students bus of 3, satisfies the precondition (6 >= 3) yet drops the third student on the floor — students.getCurrentCount() == 0 still holds, because passengerOff removes them regardless, but bus contains all passengers from \old(students) does not. The precondition that actually discharges the postcondition is bus.getCapacity() - bus.getCurrentCount() >= students.getCurrentCount(). The marked solution is the contract above, with the weaker precondition.

The loop inside that method — and why its bound is copied into a local variable before the loop starts — is taken up in java-loop-invariants.

Java Inheritance

Introduced in 2026-03-05-object-oriented-programming-i (Lecture, Week 2) — “things you have because your parents have them”.

Subclasses and superclasses

Inheritance allows creating a new class from an existing class:

  • The new class is the subclass (child/derived class).
  • The existing class it’s derived from is the superclass (parent/base class).

The running example is one Employee superclass with two subclasses:

Figure 83: The Employee inheritance example as a UML class diagram. Each box has three compartments (name / attributes / operations), with - for private and + for public, and constructors listed in the operations compartment with no return type. Generalisation is a solid line with a single unfilled triangle arrowhead entering the superclass.

This form is not a course-wide standard. The course draws inheritance in three ways: this UML three-compartment form with an unfilled triangle, a labelled box with a plain arrowhead, and a diagonal form with every edge labelled “Is a”. None of them is declared canonical. See csse2002-diagram-notation for the compartment, visibility and arrowhead conventions this figure uses.

Two things to read off the diagram before looking at any code:

  • name and address are declared private in Employee and are not repeated in either subclass. Every ContractEmployee carries them, but the subclass’s own code cannot name them — private members are not accessible in a subclass — which is what forces the super(...) call below.
  • printDetails() appears in all three boxes. That repetition is the setup for method overriding.

(The diagram writes CalcWeeklyPay() with a capital C; the code calls the same method calculateWeeklyPay(). The code spelling is the one to trust.)

extends

extends is the keyword used to implement inheritance in Java:

public class Employee {
    private String name;
    private String address;

    public Employee(String name, String address) {
        this.name = name;
        this.address = address;
    }
    public String getName() { return name; }
    public String getAddress() { return address; }
    public void setAddress(String address) { this.address = address; }
    public String printDetails() { return name + " " + address; }
}

public class ContractEmployee extends Employee {
    private double hourlyRate;
    private int hoursWorked;

    public ContractEmployee(String name, String address, double hourlyRate) {
        super(name, address);
        this.hourlyRate = hourlyRate;
        this.hoursWorked = 0;
    }
    public void logHours(int hours) { this.hoursWorked += hours; }
    public double calculateWeeklyPay() { return hourlyRate * hoursWorked; }
}

From the diagram, the shape of FullTimeEmployee is private double monthlySalary, a constructor FullTimeEmployee(String name, String address, double monthlySalary), and calcMonthlyPay() / calcAnnualPay() both returning double.

The super keyword

super is used in a subclass to access superclass members — attributes, constructors and methods.

As a constructor call, super(name, address) runs Employee’s constructor first, so the inherited name and address are initialised before the subclass’s own constructor body runs. This is not merely tidy: name and address are private in Employee, so ContractEmployee has no other way to set them.

Method overriding

The subclass inherits the attributes and methods of its superclass. If the same method is defined in both the superclass and the subclass, the subclass’s version overrides the superclass’s version — and both MUST have the same method signature (see java-encapsulation; a different signature gives you an overload, not an override).

public class Employee {
    ...
    public String printDetails() {
        return name + " " + address;
    }
}

public class ContractEmployee extends Employee {
    ...
    @Override
    public String printDetails() {
        return "Role: Contract Employee, Hourly Rate: $" + hourlyRate
             + ", Hours Worked: " + hoursWorked;
    }
}

public class FullTimeEmployee extends Employee {
    @Override
    public String printDetails() {
        return "Role: Full-Time Employee, Monthly Salary: $" + monthlySalary;
    }
}

super in an override

The superclass’s method is still reachable after overriding it. super.methodName(...) calls the superclass’s version from inside the override, so the subclass can extend the inherited behaviour rather than replace it:

public class FullTimeEmployee extends Employee {
    ...
    @Override
    public String printDetails() {
        return super.printDetails()
             + ", Role: Full-Time Employee, Monthly Salary: $" + monthlySalary;
    }
}

With Employee.printDetails() returning name + " " + address, this version prints the name and address and the role and salary, where the previous version threw the inherited half away.

Choosing whether Employee’s printDetails() or a subclass’s override actually runs for a given object is dynamic dispatch, taken up with polymorphism — see java-polymorphism and week4-tutorial-method-dispatch-and-casting.

Java I/O

Introduced in 2026-04-23-java-io (Lecture, Week 8).

Java spreads its I/O functionality across many more classes than most other languages, split roughly into three generations of API:

  1. Streams (java.io, since 1.0) — byte-oriented.
  2. Readers & Writers (java.io, since 1.1) — character-oriented, added because byte streams weren’t ideal for text/Unicode.
  3. New I/O (java.nio.file, since 1.7) — file-system operations (paths, directories, attributes), which java.io was never designed for.

Scanner (java.util, since 1.5) sits alongside these as a convenience utility — neither a stream nor a reader.

Streams

A stream is an abstraction that either produces or consumes information, letting Java perform I/O uniformly regardless of whether data comes from a file, keyboard, console, network socket, or elsewhere.

  • An output stream is an abstract destination to be written to.
  • An input stream is an abstract source of input that can be read without concern for how it’s supplied.

What the abstraction hides is threefold: the source (keyboard, disk file, network, …), the destination (terminal, disk file, network, …), and the chunking — whether data arrives one byte at a time (keyboard) or many at once (files).

How a program is written should not depend on whether its input is from a file or a keyboard, or whether its destination is a file, the console or the network. If the source or destination changes, the program should not need rewriting.

Figure 84: The stream abstraction: whatever the real source (file, console, socket), the application reads bytes through one InputStream, and writes them back out through one OutputStream, whatever the real destination.

Java has two families of streams:

  • Byte streams (java.io.InputStream / java.io.OutputStream) — raw binary data (files, images, network data).
  • Character streams (Reader/Writer, see below) — characters/text, handling Unicode; better suited to strings, text files and console text.

A byte stream reads data as bytes, whereas a character stream reads data as characters.

Reference: Java: The Complete Reference, Eleventh Edition — Herbert Schildt.

The byte-stream hierarchy

Figure 85: The byte-stream class hierarchies: OutputStream and InputStream. Each superclass sits above its subclasses, and the arrowhead points into the parent. The wrappers BufferedInputStream and BufferedOutputStream are Filter* streams — streams that wrap another stream.

InputStream and its subclasses represent a stream of bytes, drawn from different sources — FileInputStream gets bytes from a file, ByteArrayInputStream from an array, and so on. Methods that use streams should accept the superclass type as a parameter, so any concrete stream can be substituted (see java-solid-principles — Liskov Substitution).

Worked example — writing to an abstract OutputStream

System.out is an output stream already in everyday use. That makes it the first thing to hand a method that takes an abstract OutputStream: sendToStream(System.out). The version below keeps sendToStream untouched and swaps the argument twice:

public class Foo {
    public static void main(String[] args) throws IOException {
        OutputStream fos = new FileOutputStream("output.txt");
        sendToStream(fos);

        fos = new ByteArrayOutputStream();
        sendToStream(fos);

        System.out.println(fos);
    }

    private static void sendToStream(OutputStream stream) throws IOException {
        String output = "foo bar baz";
        for (char letter : output.toCharArray()) {
            stream.write(letter);
        }
        stream.flush();
    }
}

sendToStream never changes: first System.out (straight to the console), then a FileOutputStream, which leaves output.txt holding foo bar baz, then a ByteArrayOutputStream. main has to declare throws IOException; without the declaration it does not compile. The final System.out.println(fos) prints the byte-array stream’s accumulated contents, because ByteArrayOutputStream.toString() decodes the buffer it has collected.

End of file

All input streams (and everything built on them) need to consider “end of file”:

public int read() // returns -1 on end of file

Reading a whole file one byte at a time therefore loops until read() hands back -1:

public class Foo {
    public static void main(String[] args) throws IOException {
        readAll(new FileInputStream("output.txt"));
    }

    private static void readAll(InputStream input) throws IOException {
        int in = 0;
        while (in != -1) {
            in = input.read();
            System.out.println(in);
        }
    }
}

Run against an output.txt containing foo bar baz, that prints the byte values — 102, 111, 111, 32, … The fix is to cast in the println inside the loop, so you see the characters instead:

System.out.println((char) in);

The loop as written tests in before refreshing it, so the final iteration still prints the sentinel — -1, or, once cast, the char with all sixteen bits set, ￿, which is not a printable character. Reading into the loop condition, while ((in = input.read()) != -1), avoids that.

Buffering

Getting information from files can be slow a byte or char at a time. BufferedInputStream is an input stream which wraps around another input stream. The buffer is an area in the main memory used to store or hold the data temporarily. This is faster because one large read from the device then serves many small read() calls.

Only the construction changes; readAll is untouched:

readAll(new BufferedInputStream(new FileInputStream("output.txt")));

(What each layer actually contributes is drawn in Figure 86.)

On a test VM, reading a 4MB file takes 82 milliseconds with buffering and 18,193 milliseconds without.

Closing streams

Streams need closure. Streams and Readers have a close() method; systems may limit how many files you can have open at a time; when you have finished with a stream, close it.

Getting this right takes three steps. First, just catching the failure to open:

public static void main(String[] args) {
    try {
        readAll(new BufferedInputStream(new FileInputStream("output.txt")));
    } catch (IOException e) {
        System.out.println("Error: File Not Found " + e);
    }
}

That still never closes anything. Adding a finally block does — but the close can itself throw, so it needs its own try, and the whole thing gets verbose fast:

BufferedInputStream input = null;
try {
    input = new BufferedInputStream(new FileInputStream("output.txt"));
    readAll(input);
} catch (IOException e) {
    System.out.println("Error: File Not Found " + e);
} finally {
    try {
        input.close();
    } catch (IOException e) {
        System.out.println("Error closing the stream: " + e);
    }
}

try-with-resources is much cleaner — any resource declared in the try(...) parentheses is closed automatically:

try (BufferedInputStream input = new BufferedInputStream(new FileInputStream("output.txt"))) {
    readAll(input);
} catch (IOException e) {
    System.out.println("Error: File Not Found " + e);
}

Effective Java (2017, Addison-Wesley) — Item 9: “Prefer try-with-resources to try-finally”.

A cautionary example of what production I/O failures cost: a national passport office suspended issuance after a computer-system breakdown (reported November 2022).

Wrapping streams together

Nothing in java.io is one class doing everything: you assemble the behaviour you want by nesting one stream inside another. That is what the hierarchy’s whole Filter* branch is for, and why the constructor calls look the way they do. The second chain below uses InputStreamReader and BufferedReader, which the next section introduces — it is drawn here so both chains can be compared side by side.

Figure 86: How the nesting in new BufferedInputStream(new FileInputStream(...)) and new BufferedReader(new InputStreamReader(System.in)) actually behaves — each wrapper adds one capability and passes the rest through, and your code only ever holds the outermost object. BufferedInputStream wraps another input stream; InputStreamReader acts as a bridge decoding bytes into characters; BufferedReader wraps another Reader and adds readLine(). The gloss beneath each box says what that stage contributes.

Readers & Writers

Originally Java I/O was byte-oriented. Byte streams were fine for raw binary data but not ideal for text, so character streams were added in 1.1 to handle text and Unicode characters more conveniently and efficiently.

  • java.io.Writer — an abstraction over writing chars to an output.
  • java.io.Reader — an abstraction over reading chars from an input source.

Figure 87: The character-stream hierarchies: Writer and Reader, drawn the same way as Figure 85. The one two-level branch is the important one — FileReader is a kind of InputStreamReader, i.e. reading a text file is itself a case of decoding bytes into characters.

InputStreamReader is the bridge between the two systems: it wraps an InputStream (like System.in) and decodes its bytes into characters.

Worked example — read the first 10 characters of input

> Words, words, and more words
Words, wor
public class ReaderEx {
    public static void main(String[] args) throws IOException {
        readAndPrint(new InputStreamReader(System.in));
    }

    private static void readAndPrint(Reader reader) throws IOException {
        char[] letters = new char[10];
        for (int i = 0; i < 10; i++) {
            letters[i] = (char) reader.read();
        }
        System.out.println(letters);
    }
}

Exercise: rewrite the program to use FileReader. Because readAndPrint takes the abstract Reader, only the argument in main has to change.

BufferedReader

BufferedReader wraps another Reader. As well as buffering it adds String readLine():

public class BufferedReaderEx {
    public static void main(String[] args) {
        BufferedReader reader = new BufferedReader(new FileReader("readwithbuffer.txt"));
        for (int i = 0; i < 5; i++) {
            System.out.println(reader.readLine());
        }
    }
}

Wrapping System.in instead of a file is the standard console-input idiom:

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

The exception handling has to be made explicit: FileReader’s constructor throws FileNotFoundException, and readLine() throws IOException, so each needs handling. Below, the second is wrapped in an unchecked RuntimeException rather than being declared. See java-exceptions.

BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader("readwithbuffer.txt"));
} catch (FileNotFoundException e) {
    System.err.println("File not found: " + e.getMessage());
}

for (int i = 0; i < 10; i++) {
    try {
        System.out.println(reader.readLine());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

Catching and continuing leaves reader null when the file is missing, so the loop then throws a NullPointerException. try-with-resources — as used for streams above — would both scope the reader correctly and close it.

PrintWriter

System.out is a PrintStream; PrintWriter is another (better) option for character output — it can write to many destinations, and it can write formatted text. You can construct one straight from System.out:

PrintWriter printWriter = new PrintWriter(System.out);
printWriter.println("I love CSSE2002");
printWriter.printf("Formatted number: %.2f%n", 123.45336);
printWriter.flush();

Or stack it on a FileWriter inside a try-with-resources, closing both:

String fileName = "writeroutput.txt";
try (FileWriter fileWriter = new FileWriter(fileName);
     PrintWriter printWriter = new PrintWriter(fileWriter)) {
    printWriter.println("I love CSSE2002");
    printWriter.printf("Formatted number: %.2f%n", 123.45336);
    System.out.println("Successfully Written.");
} catch (IOException e) {
    e.printStackTrace();
}

writeroutput.txt then holds:

I love CSSE2002
Formatted number: 123.45

flush()

If an OutputStream/Writer is buffered, output might not be sent immediately — flush() will send any pending output. This matters for:

  • “Interactive” or other situations where you expect a response — the other end won’t respond if you haven’t actually sent anything yet.
  • Debugging or logging, where you need an up-to-date view of what is happening.

close()-ing a stream will flush it as well.

Scanner

Scanner (java.util, since 1.5) is neither a stream nor a reader — it’s a utility class that wraps an existing InputStream or Reader, added to simplify reading user input and parsing primitive types and strings, as a more user-friendly alternative to BufferedReader. It allows reading of primitive Java types from the stream, and regex scanning is possible for advanced use cases.

Because it accepts either, the same logic can be handed a Reader:

public class ScannerEx {
    public static void main(String[] args) {
        readInts(new InputStreamReader(System.in));
    }

    private static void readInts(Reader reader) {
        Scanner scanner = new Scanner(reader);
        int total = 0;
        while (scanner.hasNextInt()) {
            int newInt = scanner.nextInt();
            total += newInt;
        }
        System.out.println(total);
    }
}

or given System.in directly — in which case the Scanner internally creates its own InputStreamReader:

Scanner scanner = new Scanner(System.in);
int total = 0;
while (scanner.hasNextInt()) {
    total += scanner.nextInt();
}
System.out.println(total);

Reading strings:

  • scanner.next() — reads the next word, up to whitespace, skipping any leading whitespace.
  • scanner.nextLine() — reads the entire line, until Enter is pressed.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter three words:");
String word1 = scanner.next();   // reads up to first space
String word2 = scanner.next();
String word3 = scanner.next();
System.out.println("You entered: " + word1 + ", " + word2 + ", " + word3);

Further reading: Scanner vs. BufferedReader.

New I/O (java.nio.file)

The problem with the older java.io: it focused mainly on streams (byte and char streams), because the main goal was reading and writing data, not managing files or directories. That leaves it with limited support for file-system operations, and makes it inconvenient for file attributes, directory traversal, and path manipulation.

java.nio.file (since Java 1.7) introduces two new abstractions:

  • java.nio.file.Path — represents a file location.
  • java.nio.file.Files — utility methods for file operations.

Creating a Path

Path is the key abstraction for locating files, and can be created from path strings or from a URI:

Path p1 = Path.of("docs/output.txt");        // the whole path as one string
Path p2 = Path.of("docs", "output.txt");     // separate name elements, which Java joins into a path
Path p3 = Path.of(new URI("file:///docs/output.txt"));

Files operations

Category Methods
Create/delete Files.createFile(Path), Files.createDirectory(Path), Files.delete(Path), Files.deleteIfExists(Path)
Query Files.exists(Path), Files.isDirectory(Path), Files.isRegularFile(Path)
Manipulate Files.copy(Path, Path), Files.move(Path, Path)
Read/write Files.readAllLines(Path), Files.readString(Path), Files.write(Path, Iterable<? extends CharSequence>), Files.writeString(Path, CharSequence)

CharSequence is an interface representing a read-only sequence of characters; String, StringBuilder, StringBuffer and CharBuffer all implement it.

public static void main(String[] args) throws IOException {
    Path myPath = Path.of("src", "Week08", "NIO", "myfile.txt");
    Files.createFile(myPath);
}

Reading a whole file is then a one-liner — no stream, no wrapper, no close():

public static void main(String[] args) throws IOException {
    Path myPath = Path.of("src", "Week08", "NIO", "myfile.txt");

    List<String> lines = Files.readAllLines(myPath);
    for (String line : lines) {
        System.out.println(line);
    }
}

Exercise: rewrite the earlier stream and reader exercises using New I/O.

Summary: which to use?

  • Streams — good for binary data (byte at a time).
  • Readers & Writers — best for text data.
  • New I/O — when manipulating a file system or file contents.

Saving and loading a whole object model to a file is picked up later, in week10-lab-java-io.

Java JUnit

Introduced in 2026-03-26-testing (Lecture, Week 5). See java-testing for the broader testing concepts JUnit is used to implement.

What is JUnit?

An open-source test automation framework for Java — one of many xUnit frameworks (JUnit, NUnit, CPPUnit, PyUnit…). This course uses JUnit 4 (http://junit.org/junit4, and the cookbook at https://junit.org/junit4/cookbook.html). Depending on how software is structured, unit-testing frameworks like JUnit can also be used for other kinds of automated testing, but “unit testing” is sometimes incorrectly used to mean any automated test.

Writing tests

Tests are defined in classes — one test class per real class. @Test marks a method as a test JUnit should run; test methods take no parameters and return void, and should be named for what they check.

Figure 88: One test class per real class: Person produces PersonTest, which imports org.junit.Test and carries one @Test-annotated method per thing being checked. The hollow block arrow pointing down means produces/translates-to. The Person snippet does not compile as drawn: getAge() returns name, which the snippet never declares, and the field is typed String age. The full Person below types it int and is the version that compiles.

The full class and its test class:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}
import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class PersonTest {

    @Test
    public void TestGetAge() {
        Person p1 = new Person("Jack", 10);
        int age = p1.getAge();
        assertEquals(10, age);
    }

    @Test
    public void TestGetName() {
        Person p1 = new Person("Jack", 10);
        String name = p1.getName();
        assertEquals("Jack", name);
    }
}

The test class uses two imports: org.junit.Test for the annotation, and a static import of org.junit.Assert.assertEquals so the assertion can be called bare rather than as Assert.assertEquals(...).

@Before and @After

Each test method should be independent, but you may want common things set up before each test (e.g. object creation):

public class PersonTest {

    private Person person;

    @Before
    public void setUp() {
        person = new Person("Jack", 10);
    }

    @After
    public void tearDown() {
        person = null;
    }
    // ...
}

@Before will be run before each test; @After will be run after each test. Every test method gets a freshly built fixture rather than whatever the previous test left behind, which is how the tests are kept independent.

Assert

Some static methods in Assert:

  • assertEquals — asserts that two objects are equal.
  • assertArrayEquals — asserts that two object arrays are equal.
  • assertFalse / assertTrue — asserts that a condition is false or true.
  • assertSame / assertNotSame — asserts that two objects refer to the same object or not.

The difference between assertSame and assertEquals is reference identity vs .equals: two distinct Person objects with the same fields can be assertEquals-equal (if equals is overridden) but are never assertSame.

Checking for exceptions

Don’t catch the exception — the test runner does. Tell the test runner which exception it should catch, via @Test(expected = ...):

@Test(expected = EOFException.class)
public void testExceptions() throws EOFException {
    callThatShouldThrowEOFException();
}

.class is required after the name of the class. The test passes if that exception is thrown and fails if it is not, or if a different one is. See java-exceptions.

Black box tests in JUnit

Write the tests purely from the specification/Javadoc, without looking at the implementation, then use smoke tests, boundary tests and equivalence classes (see java-testing) to decide what to check. The hard constraint is that tests must not violate preconditions. A test that breaks @requires tells you nothing, because the method is entitled to do anything at all in that case.

White box tests in JUnit

Design tests based on the internal logic. You try to cover branches, loops and edge cases, and you may aim for a code coverage target (e.g. 100%).

The worked example is a discount calculator with two nested levels of branching:

public class DiscountCalculator {

    public double calculateDiscount(double amount, boolean isMember) {
        if (amount <= 0) {
            return 0;
        }

        if (isMember) {
            if (amount > 100) {
                return amount * 0.2;
            } else {
                return amount * 0.1;
            }
        } else {
            if (amount > 100) {
                return amount * 0.1;
            } else {
                return 0;
            }
        }
    }
}

Figure 89: Why DiscountCalculator needs exactly five tests: the method as a decision tree, one leaf per test. Each box is a condition from the method or the return its branch reaches, so the expected values in the tests can be read off the leaves. The magenta (amount, isMember) pair under each leaf is the argument list of the test that reaches that leaf. The early return on amount <= 0 is the one leaf covered by two assertions in a single test, which is why it carries two pairs.

The five tests, one per leaf:

public class DiscountCalculatorTest {

    DiscountCalculator calc = new DiscountCalculator();

    @Test
    public void testAmountLessOrEqualZero() {
        assertEquals(0.0, calc.calculateDiscount(0, true));
        assertEquals(0.0, calc.calculateDiscount(-10, false));
    }

    @Test
    public void testMemberAbove100() {
        assertEquals(40.0, calc.calculateDiscount(200, true));
    }

    @Test
    public void testMemberBelowOrEqual100() {
        assertEquals(10.0, calc.calculateDiscount(100, true));
    }

    @Test
    public void testNonMemberAbove100() {
        assertEquals(20.0, calc.calculateDiscount(200, false));
    }

    @Test
    public void testNonMemberBelowOrEqual100() {
        assertEquals(0.0, calc.calculateDiscount(100, false));
    }
}

Two things worth reading off this example:

  • The tests are named for the branch they cover, not for the method (testMemberAbove100, not testCalculateDiscount3), which is what naming a test for what it checks looks like in practice.
  • amount = 100 is the argument in two of the five tests. It is the boundary of amount > 100, so it is both a white-box branch probe and a black-box boundary test.
NoteassertEquals on doubles

The tests above call assertEquals(0.0, ...) on double values. JUnit 4’s two-argument assertEquals(double, double) is deprecated precisely because floating-point equality is unreliable; the three-argument assertEquals(expected, actual, delta) is the form that compiles without a deprecation warning. The code above will warn if you type it in.

Java Lambdas and Streams

Introduced in 2026-05-14-lambdas-streams-and-events (Guest lecture, Week 11). Practised further in week12-tutorial-lambdas-and-streams.

Lambdas (anonymous functions)

A lambda is a function as a value — it isn’t declared with a name, and can be passed around like any other reference value, such as an object. JavaScript and Python have the same idea.

Scope: like in most languages, a Java lambda can hold references to things accessible in scope at the time of creation.

Functional interfaces

Because Java is typed, you cannot have an anonymous function without clearly defined type information — the JVM would not know what to do. So Java supplies a set of interfaces that are combined with generics (see java-generics) to give easily-adjustable type descriptions for lambdas. They live in java.util.function. Four of them:

Interface Signature Purpose
Consumer<T> takes a T, returns nothing (void) by convention indicates the function has some kind of side effect — if it returned nothing and had no side effect it would do nothing at all
Predicate<T> takes a T, returns boolean useful in filtering especially
Function<T, R> takes a T, returns an R turning a T into an R
BiFunction<T, U, R> takes a T and a U, returns an R deriving one value from two, e.g. the distance between two positions, or custom sorting

A minimal lambda of each shape:

Consumer<String> print = s -> System.out.println(s);
Predicate<Integer> isEven = n -> n % 2 == 0;
Function<String, Integer> length = s -> s.length();
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;

Consumer<T> is the one that matters most for events: the toy event system in java-events types every listener as a Consumer<SimpleEvent>.

Streams

Added in Java 8 to enable a different, more declarative style of programming. Brian Goetz’s IBM article on Java streams is a very good resource on their benefits.

This style is particularly effective when you have data you need to conduct multiple operations on sequentially, or retrieve a single resulting value from a sequence of operations, which is often the case in a real job. At a simple level they are an alternative to writing lots and lots of very samey for loops over a sequential set of data (most often a List or similar, see java-collections-framework); the JavaScript equivalents are .filter(), .map() and .reduce().

The worked example

One pipeline, taken a line at a time:

int totalHpFromFireEnemies =
    enemies.stream()
        .filter(enemy -> enemy.faction.equals("Fire"))
        .mapToInt(enemy -> enemy.hp)
        .sum();
Stage Line What it does
.stream() enemies.stream() opens a stream over the collection
.filter() .filter(enemy -> enemy.faction.equals("Fire")) drops every enemy whose faction isn’t Fire
.mapToInt() .mapToInt(enemy -> enemy.hp) replaces each surviving Enemy with its int hp
.sum() .sum() reduces what is left to a single total

Figure 90: The stream example as a pipeline, one stage per line of the chain. Each box is the type between stages: .stream() turns the list into a Stream<Enemy>, .filter() takes a Predicate and hands on a Stream<Enemy>, .mapToInt() hands on an IntStream, and .sum() collapses it to one int. The braces mark the intermediate operations and the terminal operation.

Anatomy of a stream pipeline

A pipeline has three steps:

  1. Start a stream with .stream().
  2. Chain any number of intermediate operations: .filter() | .map() | .distinct() | .sorted() | .mapToInt() etc.
  3. Resolve it into a final value with one of the terminal operations: .sum() | .count() | .toList() | .collect() | .reduce().

You chain the first kind and resolve with the second. The rule underneath: an intermediate operation hands on another stream, a terminal one resolves to a value. That is what puts .mapToInt() in the first list and .sum() in the second, and why exactly one terminal operation ends a pipeline.

Java Loop Invariants

Introduced in 2026-05-21-correct-programming (Lecture, Week 12). Extends java-hoare-logic’s backward-reasoning technique to loops, where the number of iterations isn’t known up front.

…proving the correctness of algorithms has another aspect that is even more important: it mirrors the way we understand an algorithm.

— Donald Knuth, The Art of Computer Programming (Vol. 1), 1997

What is an invariant?

An invariant is a property of a system that does not change.

Motivating puzzle

A jar contains 100 red and 100 blue beans. Repeatedly: pick two random beans; if they’re the same colour, discard both; if they’re different colours, discard the blue one. What colour is the last bean?

Let \(r, b\) be the current counts of red/blue beans. Each step does exactly one of:

Pick Action Effect
two reds discard both \(r \mapsto r - 2,\ b \mapsto b\)
two blues discard both \(r \mapsto r,\ b \mapsto b - 2\)
one of each discard blue \(r \mapsto r,\ b \mapsto b - 1\)

What never changes? The parity of \(r\) — every action either leaves \(r\) unchanged or decreases it by exactly 2, so \(r\) stays even throughout (it starts at 100, itself even). When one bean remains, \(r + b = 1\); since \(r\) must be even, \(r \neq 1\), so \(r = 0\) and \(b = 1\) — the last bean is blue.

The property “\(r\) is even” is an invariant of the process: it (1) holds before any step, (2) is preserved by every step, and (3), combined with the termination condition (\(r + b = 1\)), implies what we wanted to prove. This is exactly the structure of a loop invariant.

Loop invariants

A loop invariant is a condition that: (1) holds before the loop is entered, (2) is preserved by each iteration, and (3) combined with the negation of the guard, implies the postcondition.

Those three clauses are three separate proof obligations, and they attach to three different places around the loop:

Figure 91: The three obligations in the definition above, each pinned to the point in the loop where it has to be discharged. The invariant point is the top of the loop, before the guard is tested: establishment is the arrow into it, preservation is the arrow back to it, and exit is what the guard’s failure adds to it. Connectors are teal and assertions are green.

None of the three clauses in Figure 91 says anything about the loop finishing. An invariant that survives all three checks establishes only “if the loop ends, the postcondition holds”; termination is a separate argument — in power below, that exp - i strictly decreases and is bounded below.

int count = 0;
while (count < n) {
    // invariant: count >= 0
    count = count + 1;
}
// {0 >= 0}
int count = 0;
// {count >= 0}                    <-- invariant holds before the loop
while (count < n) {
    // invariant: count >= 0
    // {count + 1 >= 0}
    count = count + 1;
    // {count >= 0}                <-- preserved by the body
}
// {count >= 0 && count >= n}

Deriving an invariant for power

/**
 * @requires ????
 * @ensures \result == base^exp
 */
int power(int base, int exp) {
    int result = 1;
    int i = 0;
    while (i < exp) {
        result = result * base;
        i = i + 1;
    }
    return result;
}

Step 1 — guess an invariant. Replace exp in the postcondition with the loop variable i: \(I : \text{result} = \text{base}^i\).

Step 2 — verify. Three checks:

  1. Does \(I\) hold before the loop first executes? result = base^i \(\equiv 1 = \text{base}^0 \equiv\) true. ✓
  2. Assuming \(I\) holds at the top of the loop body, does it still hold after? result * base = base^i * base = base^{i+1}, and after i = i + 1, that’s exactly result = base^i again. ✓
  3. Does \(I\) combined with the negated guard (\(i \geq \text{exp}\)) imply the postcondition? result = base^i \(\land\ i \geq \text{exp} \Rightarrow \text{result} = \text{base}^{\text{exp}}\)? Not quite — we can only conclude \(i \geq \text{exp}\), but we need \(i = \text{exp}\).

Step 3 — strengthen. Add the bound \(i \leq \text{exp}\) to the invariant: \(I : \text{result} = \text{base}^i \land i \leq \text{exp}\). Re-checking: \(I\) now holds initially iff \(\text{exp} \geq 0\) (giving us our precondition), is still preserved by the loop body, and combined with \(i \geq \text{exp}\) now forces \(i = \text{exp}\) exactly, giving the postcondition:

/**
 * @requires exp >= 0
 * @ensures \result == base^exp
 */
int power(int base, int exp) {
    // {0 <= exp}
    // {1 == base^0 && 0 <= exp}
    int result = 1;
    int i = 0;
    // {result == base^i && i <= exp}
    while (i < exp) {
        ...
    }
    // {result == base^i && i <= exp && i >= exp}
    // {result == base^exp}
    return result;
}

The precondition comes from obligation (1) of Figure 91, failing, and being read backwards. exp >= 0 was never designed in — it is whatever the establishment check needed in order to succeed.

Designing an algorithm from an invariant: fast exponentiation

The power above runs in \(O(\text{exp})\) multiplications. We can do better using the identity:

\[b^e = \begin{cases} (b^{e/2})^2 & \text{if } e \text{ is even} \\ b \times (b^{(e-1)/2})^2 & \text{if } e \text{ is odd} \end{cases}\]

E.g. computing \(3^{13}\): \(3^{13} = 3 \times 3^{12}\) [13 odd] \(= 3 \times (3^2)^6\) [12 even] \(= 3 \times 9^6 = 3 \times (9^2)^3\) [6 even] \(= 3 \times 81^3 = 3 \times 81 \times 81^2\) [3 odd] \(= 3 \times 81 \times 6561 = 1{,}594{,}323\) — only a handful of multiplications instead of 12 sequential ones.

Design from the invariant: rather than writing code and then finding its invariant, pick the invariant first and let the code follow. We want a loop maintaining:

\[I : \text{result} \times b^e = \text{base}^{\text{exp}}\]

starting from result = 1, b = base, e = exp, terminating when e == 0:

/**
 * @requires exp >= 0
 * @ensures \result == base^exp
 */
int power(int base, int exp) {
    int result = 1;
    int b = base;
    int e = exp;
    while (e > 0) {
        // invariant: result * b^e == base^exp
        if (e % 2 == 1) {
            result = result * b;
            e = e - 1;
        }
        b = b * b;
        e = e / 2;
    }
    return result;
}

Verifying \(I\) (using \(b^e = (b^{e/2})^2\) when even, \(b \times (b^{(e-1)/2})^2\) when odd, and \((a^b)^c = (a^c)^b\)):

  1. Before the loop: result * b^e == base^exp \(\equiv 1 \times \text{base}^{\text{exp}} = \text{base}^{\text{exp}} \equiv\) true. ✓
  2. Through the body: splitting on e % 2, both branches reduce back to exactly result * b^e == base^exp after the update (the if branch peels off one factor of b into result and decrements e first; both branches then square b and halve e). ✓
  3. On exit (e <= 0): result * b^e == base^exp with e <= 0 only concludes the postcondition when e >= 0 too (i.e. e == 0) — which holds as long as exp >= 0, giving the same precondition as before. ✓

The invariant is easiest to believe by watching it not move. Running the loop on the same \(3^{13}\) worked above:

Figure 92: The fast-power loop traced on power(3, 13), one box per arrival at the top of the loop. The three variables change on every step; the product result * b^e underneath does not, and the five products it takes are exactly the chain the section above works by hand (the section’s 3 x 81 x 6561 and this trace’s 243 x 6561 are the same number). Connectors are teal and the invariant is green.

This preserves the exact same specification as the slow version — both satisfy @requires exp >= 0 / @ensures \result == base^exp — but the fast version reaches it in \(O(\log \text{exp})\) multiplications instead of \(O(\text{exp})\).

Invariants in the Week 12 exercises

Neither Week 12 exercise set is about correctness — the applied class is lambdas and streams (week12-tutorial-lambdas-and-streams) and the practical is generics (week12-lab-generics) — but both contain loops whose behaviour is only explicable in these terms, and the practical writes contracts for two of them.

The loop bound that must not move

The practical’s transferStudents (Task 4) empties one bus into another. Its loop carries a one-line comment:

// Ensure loop condition does not change while iterating
int numStudents = students.getCurrentCount();
for (int i = 0; i < numStudents; i++) {
    Concession student = students.passengerOff();
    bus.passengerOn(student);
}

The contract this loop has to establish is its @ensure (given in full in java-hoare-logic), whose first clause is students.getCurrentCount() == 0. Taking the invariant at the top of the iteration with counter i to be

0 <= i && i <= numStudents && students.getCurrentCount() == numStudents - i, and bus holds everything it started with plus the i students already moved,

the three obligations of Figure 91 go through: at i == 0 nothing has moved and getCurrentCount() is still numStudents; each iteration takes exactly one passenger off and puts exactly one on before i++, restoring it; and exiting with i == numStudents gives students.getCurrentCount() == 0 together with all numStudents students on bus.

Now write the guard the obvious way instead, reading the count live, and the invariant has nothing to hold onto: i climbs by one per iteration while students.getCurrentCount() falls by one, so the two meet halfway and the loop stops with half the bus still loaded.

Figure 93: Why the practical snapshots its loop bound. Both columns run the same body on a source bus of four; the left column is the loop with the bound read once into numStudents, the right is the same loop with students.getCurrentCount() in the guard. Reading the count live makes the guard chase a quantity the body is decreasing, and the two meet after two iterations. Bus contents are drawn as array rows and the verdict on each column is in magenta.

In general the live-bound version runs \(\lceil n/2 \rceil\) iterations and leaves \(\lfloor n/2 \rfloor\) students behind, because i and the count meet at \(i = n - i\). The fix is the standard one: a loop guard should not read state the body is mutating. Copying the bound into a local before the loop is what turns numStudents into something the invariant can be stated against. Task 5’s transferAllConcession uses the same body and the same snapshot, with the type parameter T in place of Concession, so the same invariant carries over unchanged.

An accumulator loop inside a lambda

The applied class’s Task 9 hides an ordinary counting loop inside a Function:

Function<Integer, Integer> factorial = n -> {
    int result = 1;
    for (int i = 2; i <= n; i++) {
        result *= i;
    }
    return result;
};
System.out.println(factorial.apply(4));   // 24

The task asks only for the printed value. The invariant, following the power recipe of replacing the target quantity’s bound with the loop variable, is \(I : \text{result} = (i-1)!\ \land\ 2 \leq i \leq n+1\):

  1. Establishment. At the top, i == 2 and result == 1 == 1!. ✓ — but the bound clause needs \(2 \le n+1\), so this invariant establishes only for n >= 1, which is the derived precondition. (factorial.apply(0) still returns 1, correctly; that just isn’t something this invariant proves.)
  2. Preservation. result * i == (i-1)! * i == i!, and i++ then makes that (i-1)! again. ✓
  3. Exit. The guard fails at i > n, which with i <= n + 1 forces i == n + 1, so result == n!. ✓

At n == 4 that is 4! == 24, derived rather than simulated.

The same idea, written into a method signature

The applied class’s Task 18 computes the same shape of thing with no loop at all:

Stream<Integer> stream = Stream.iterate(1, n -> n * 2).limit(5);
Integer result = stream.reduce(0, (a, b) -> a + b);   // 31

reduce’s first argument is the identity and its second is the step. Read as a loop, those are precisely obligations (1) and (2): the identity 0 establishes the invariant “the accumulator holds the sum of the elements consumed so far”, and (a, b) -> a + b is the step that preserves it. When the stream runs out — the negated guard — the accumulator holds the sum of all five elements, \(1 + 2 + 4 + 8 + 16 = 31\). Nothing about the reasoning has changed; the fold’s signature just makes you write the invariant’s two halves down where a for loop would have let you leave them implicit. See java-lambdas-and-streams for reduce itself.

Pragmatic considerations

Proving correctness can be vital, but it’s also time-consuming — you want code running on a plane or controlling trains to be correct; you may not care nearly as much whether a weekend web-scraping script is correct. Where formal reasoning tends to pay off:

  • Combinatorial algorithms — proving a faster/trickier implementation still satisfies the original spec (as with power above).
  • Distributed and concurrent algorithms — notoriously hard to reason about by testing alone (see CSSE3610/7610).

Reasoning about programs this way provides (1) a more rigorous way to think about your software, and (2) a better interface design for others to interact with it — it doesn’t remove the need to think about your programs, but gives a framework to structure that thinking.

A loop invariant is not the only kind of invariant in this course: a class invariant is the same idea applied to an object’s fields across every public method rather than to a loop’s variables across every iteration — established by the constructor, preserved by each method, relied on by all of them. See week8-tutorial-class-invariants.

Beware of bugs in the above code; I have only proved it correct, not tried it.

— Donald Knuth (memo to Peter van Emde Boas, 1977)

Java Mutability

Introduced in 2026-03-12-object-oriented-programming-ii (Lecture, Week 3). Builds on java-encapsulation.

Mutable vs immutable classes

Objects in Java can either change their state after creation or remain fixed forever.

Two types of class design:

  • Mutable class — object state can change after creation.
  • Immutable class — object state cannot change after creation.

Mutable

State is reachable through setters, so it can change at any point in the object’s life:

public class Person {
    private String name;
    private int age;

    public void setName(String name) { this.name = name; }
    public void setAge(int age) { this.age = age; }
}
class Main {
    public static void main(String[] args) {
        Person p = new Person();
        p.setName("Alice");
        p.setAge(20);

        p.setAge(30);   // state changed
    }
}

This object can change at any time.

Immutable

The immutable version changes four things at once: the class is final, both fields are final, the values arrive through the constructor, and there are no setters — only getters.

public final class Person {
    private final String name;
    private final int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() { return name; }
    public int getAge() { return age; }
}
class Main {
    public static void main(String[] args) {
        Person p1 = new Person("Alice", 20);
        Person p2 = new Person("Bob", 30);
        System.out.println(p1.getName() + " " + p1.getAge());
    }
}

Changing a value now means constructing a new object, not mutating the old one.

Why final on the class

A subclass can introduce mutability (Effective Java (2nd ed.), Item 16, page 78). If the class is subclassable, a subclass can add mutable state or override methods to return values that vary, so callers can no longer rely on “an instance of this type never changes”. Marking the class final is what forecloses that.

Arrays and lists break naive immutability

Even if a class looks immutable, it may not be.

final on an array field only prevents reassigning the reference. It does nothing to protect the array’s contents, and a getter that returns the field hands the caller a live handle on the object’s own state:

public final class Person {
    private final String name;
    private final String[] phoneNumbers;

    public Person(String name) {
        this.name = name;
        this.phoneNumbers = new String[]{"111", "222"};
    }

    public String getName() { return name; }

    public String[] getPhoneNumbers() { return phoneNumbers; }
}
class Main {
    public static void main(String[] args) {
        Person person = new Person("John");
        person.getPhoneNumbers()[0] = "999999";

        System.out.println(person.getPhoneNumbers()[0]);   // 999999
    }
}

Every field is private final and there is not a setter in sight, yet the object’s state changed. The rule:

  • final for arrays means the reference cannot change, not the contents.
  • final prevents reassigning the array:
this.phoneNumbers = new String[]{"123"}; // NOT allowed if already assigned

Defensive copying

To protect mutable objects, create copies — on the way in and on the way out, so neither the constructor’s caller nor the getter’s caller keeps a handle on the field (Effective Java, Item 50: “Make defensive copies when needed”):

public final class Person {
    private final String name;
    private final String[] phoneNumbers;

    public Person(String Name, String[] phoneNumbers) {
        this.name = Name;
        this.phoneNumbers = phoneNumbers.clone();   // defensive copy
    }

    public String[] getPhoneNumbers() {
        return phoneNumbers.clone();                // defensive copy
    }
}

Figure 94: Why a class whose getter returns its array field is not immutable, and what .clone() changes. Left: the field and the getter’s return value are the same array, so the caller’s write lands in the object’s state. Right: the getter hands out a copy, so the write lands somewhere the object does not care about.

clone() on an array is a shallow copy — it duplicates the row of references, not the objects they point at. That is enough here because String is itself immutable, but a Person[] of mutable Person objects would still leak.

Java Polymorphism

Introduced in 2026-03-12-object-oriented-programming-ii (Lecture, Week 3). Practised in week4-tutorial-method-dispatch-and-casting.

What is polymorphism?

From the Greek “poly” (many) and “morphe” (form). In programming, it allows the same method call to produce different behaviour depending on the object that executes it.

There are three named kinds. The first two differ in when the method body is chosen; the third is about what types a call site will accept.

Figure 95: The two selection mechanisms. Left: overloading is resolved by the compiler from the argument’s compile-time type, so the choice is fixed once the file compiles. Right: overriding is resolved by the JVM from the object actually on the other end of the reference; the arrow from myAnimal.makeSound() to Dog.makeSound() means the call dispatches to that method.

Compile-time polymorphism (method overloading)

Method overloading occurs when multiple methods have the same name but different parameter lists (different type, number, or both). The method to be executed is determined at compile time based on the method signature.

Which one runs is decided from the signature (see java-encapsulation) before the program ever runs:

public class CompPolymorphism {
    static String print(int value) {
        return "number";
    }
    static String print(String value) {
        return "text";
    }

    public static void main(String[] args) {
        System.out.println(print(21));    // number
        System.out.println(print("21"));  // text
    }
}

Runtime polymorphism (dynamic method dispatch)

  • Runtime polymorphism is also known as dynamic method dispatch.
  • It occurs when the method that gets executed is determined at runtime based on the actual object type, not the variable type.
  • It is implemented through method overriding — when a subclass provides a specific implementation for a method already defined in its superclass, the subclass’s method is the overridden method (see java-inheritance).

The rule:

The subclass’s overriding method executes, regardless of the compile-time type of the subclass instance. — Effective Java

The example below reassigns the same variable: nothing about the variable changed, only the object it points at.

public class Animal {
    public void makeSound() { System.out.println("Animal makes a sound"); }
}
public class Cat extends Animal {
    @Override public void makeSound() { System.out.println("Cat meows"); }
}
public class Dog extends Animal {
    @Override public void makeSound() { System.out.println("Dog barks"); }
}
public class TestPolymorphism {
    public static void main(String[] args) {
        Animal myAnimal = new Dog();
        myAnimal.makeSound();   // Dog barks

        myAnimal = new Cat();
        myAnimal.makeSound();   // Cat meows
    }
}

Even though the object type is Animal, the Dog version of makeSound() runs because the actual object is Dog.

Subtype polymorphism

  • Subtype polymorphism occurs when objects of different subclasses can be treated as objects of a common superclass or interface.
  • This is possible because subclasses are subtypes of their superclass.
  • It is achieved through inheritance (extends) or interface implementation (implements).
  • It allows code to work with the abstraction (supertype) instead of specific implementations.

The rule the whole idea rests on:

A subclass object can be used anywhere a superclass is expected.

Where runtime polymorphism is about which body runs, subtype polymorphism is about what a call site will accept: performAnimalSound is written once against Animal and never mentions Dog or Cat.

public class TestSubtypePolymorphism {
    public static void main(String[] args) {
        Animal myAnimal = new Dog();

        performAnimalSound(myAnimal);   // a Dog object
    }

    public static void performAnimalSound(Animal animal) {
        animal.makeSound();             // Outputs: Dog barks
    }
}

The same method works unchanged when the supertype is an interface rather than a superclass. Any class that implements the interface can be passed:

public interface Animal {
    void makeSound();
}

public class Cat implements Animal {
    @Override public void makeSound() { System.out.println("Cat meows"); }
}
public class Dog implements Animal {
    @Override public void makeSound() { System.out.println("Dog barks"); }
}
public class TestSubtypePolymorphism {
    public static void main(String[] args) {
        performAnimalSound(new Dog());
        performAnimalSound(new Cat());
    }

    public static void performAnimalSound(Animal animal) {
        animal.makeSound();
    }
}

Choosing between the two supertypes is the interface-vs-abstract-class question — see java-abstraction.

How it connects to casting

Assigning new Dog() to an Animal variable is an implicit upcast (java-casting). That is why the declared type restricts what you may call (myAnimal.climb() will not compile even when the object is a Cat) while the actual object still decides what runs — the left and right halves of Figure 95 are the same reference seen from the compiler’s side and the JVM’s side.

Java Primitive and Reference Types

Introduced in 2026-02-26-course-overview-and-java-basics (Lecture 1, Week 1).

Two categories of types

Java distinguishes two sorts of types:

  1. Primitive types — built-in, fixed representations.
  2. Reference types — everything else (i.e. classes), including String, arrays, and any user-defined class.

Primitive types

Type Size Stores
boolean not specified true or false
byte 1 byte / 8 bits whole numbers from -128 to 127
short 2 bytes / 16 bits whole numbers from -32,768 to 32,767
int 4 bytes / 32 bits whole numbers from -2,147,483,648 to 2,147,483,647
long 8 bytes / 64 bits whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 4 bytes / 32 bits fractional numbers, accurate to 6-7 decimal places
double 8 bytes / 64 bits fractional numbers, accurate to 15 decimal places
char 2 bytes / 16 bits a single character/letter

The JVM does not specify a width for boolean.

Reference types

Reference types are everything that isn’t primitive — classes, including String and arrays. A variable of a reference type stores a reference to an object, not the object’s data directly. That difference is visible in the runtime memory model: a primitive’s value lives in the method’s stack frame, while a reference type’s frame slot holds only an arrow at a heap object.

Figure 96: The difference that everything else follows from, in a trace of lastMark(5): the primitive int n is stored as a value in the stack frame, while the reference float[] marks stores only an arrow at an object on the heap. The stack is the open-topped container, the heap is the rounded region, and the reference is the teal arrow.

Why the distinction matters

Assignment and equality mean different things on each side. x == y compares stored values only for primitive types:

Primitive types Reference types
x = y make x store a copy of y’s value make x refer to the same object y refers to
x == y check if x stores the same value as y check if x refers to the same object as y
x != y check if the value stored in x differs from y’s check if x and y reference different objects

So on reference types you almost always want .equals(), not == — see 2026-02-26-java-basics-part-02-collections-and-strings for the String pooling example that makes this concrete, and for how the stack/heap split follows from it.

Wrapper classes

Collections (Stack, List, Set, Map) can only store objects/reference types, so Java provides a class for each primitive type:

Primitive Wrapper class
boolean Boolean
byte Byte
char Character
double Double
float Float
int Integer
long Long
short Short

Stack<int> is illegal; Stack<Integer> is what you write. See java-collections-framework.

Java Refactoring

Introduced in 2026-04-02-refactoring (Lecture, Week 6). Practised in week9-lab-refactoring.

What is refactoring?

A disciplined technique for continuously restructuring an existing body of code, altering its internal structure without changing its external behaviour.

Two halves make it a technique rather than a mood: continuous (not a one-off clean-up) and behaviour-preserving (the outside of the system cannot tell you did it). See also refactoring.guru.

Why refactor?

Over time, as features are added: quick fixes (“hacks”) accumulate, the design becomes messy, and code becomes harder to change.

Good practice

  • Don’t refactor and add functionality at the same time — keep the two activities separate.
  • Have good tests before refactoring, so you’ll know immediately if you’ve broken something (see java-testing, java-junit). This is what puts Refactor where it is in the development cycle, drawn in 2026-04-02-refactoring: you only ever enter it from a passing test.
  • Take short, deliberate steps: move a member variable, split a method, rename a variable. Refactoring is usually many small, localised changes that add up to a larger-scale change — small steps + testing after each one avoids prolonged debugging.
  • Refactor early, refactor often.

When to refactor

There are two triggers: refactor when it would make the next change easier to add, and refactor when it would make the code easier to understand. Code smells (below) are a third: symptoms that point at where one of the first two applies.

Example: making it easier to add a feature

A Vehicle class using a type string and a chain of if/else branches is fragile to extend. Adding a scooter means adding the same else if (type.equals("scooter")) { return ..; } block three times over — one for each place in the codebase that switches on type. Adding one vehicle is not one edit, it is an edit everywhere the string is tested, and nothing tells you when you have found them all.

public class Vehicle {
    private String type;

    public Vehicle(String type) { this.type = type; }

    public int travelTime(int distance) {
        if (type.equals("car")) {
            return distance / 80;
        } else if (type.equals("bike")) {
            return distance / 20;
        }
        return distance;
    }
}

Refactored to use inheritance/polymorphism (see java-polymorphism), adding a Scooter is just one new class — no existing code needs editing:

abstract class Vehicle {
    public abstract int travelTime(int distance);
}
class Car extends Vehicle {
    @Override
    public int travelTime(int distance) { return distance / 80; }
}
class Bike extends Vehicle {
    @Override
    public int travelTime(int distance) { return distance / 20; }
}
class Scooter extends Vehicle {
    @Override
    public int travelTime(int distance) { return distance / 5; }
}

The refactoring has moved where a new vehicle type lands. Before, it lands in the middle of an existing method (and in every other method that branches on type); after, it lands in a new leaf of the hierarchy that nothing existing has to know about:

Figure 97: Adding a scooter, before and after. Left: one class, and the new type is another branch spliced into an existing method — the red outline marks the edit. Right: an abstract Vehicle with one subclass per type, joined by a connector with a single arrowhead into the parent. The new type is a whole new box that no existing box points at, again outlined in red.

What has not changed: travelTime(int distance) still exists and still returns the same answers for cars and bikes. That is what makes this a refactoring rather than a rewrite. The Vehicle abstraction being open to new subclasses without being edited is the Open-Closed Principle arriving early — see java-solid-principles.

Example: making it easier to understand

The second trigger. Here nothing about the structure changes — the same three branches run in the same order — but the conditions are replaced by named boolean-returning methods, so the reader sees the intent of a branch instead of re-deriving it from raw comparisons every time:

// Before
private int temperature;
private boolean isRaining;
public void provideWeatherAdvice() {
    if (temperature > 25 && !isRaining) {
        wearSunscreen();
        hydrate();
    } else if (temperature <= 25 && !isRaining) {
        play();
    } else if (isRaining) {
        equipUmbrella();
    }
}
// After
private int temperature;
private boolean isRaining;
public void provideWeatherAdvice() {
    if (isHotAndSunny()) {
        wearSunscreen();
        hydrate();
    } else if (isPleasant()) {
        play();
    } else if (isRaining) {
        equipUmbrella();
    }
}

isRaining is left as it was, because a field already named for the condition it tests reads fine — only the two compound conditions needed a name. The bodies of the extracted methods (isHotAndSunny(), isPleasant()) are the conditions they replaced.

Code smells

A “code smell” is a surface indication that usually corresponds to a deeper problem in the design. Three are worked here.

Bad naming

Single-letter and cryptic names force the reader to trace the logic before they can know what it is for. The two snippets compile to the same thing; only the second one tells you it counts even numbers:

// Before
int r = 0;
for (int x : y) {
    if (g(x)) {
        r++;
    }
}
return r;
// After
int evenCount = 0;
for (int number : numbers) {
    if (isEven(number)) {
        evenCount++;
    }
}
return evenCount;

Every name is renamed, including the loop variable and the collection — r → evenCount, x → number, y → numbers, g → isEven.

Duplication

Near-identical blocks repeated for different data. Two arrays, two copy-pasted loops; a fix to one has to be remembered for the other:

// Before
int[] first = new int[]{1, 2, 3};
int[] second = new int[]{4, 5, 6};

int firstSum = 0;
for (int i = 0; i < 3; i++) {
    firstSum += first[i];
}
int firstAverage = firstSum / 3;

int secondSum = 0;
for (int i = 0; i < 3; i++) {
    secondSum += second[i];
}
int secondAverage = secondSum / 3;
// After
int[] first = new int[]{1, 2, 3};
int[] second = new int[]{4, 5, 6};

int firstAverage = average(first);
int secondAverage = average(second);

int average(int[] numbers) {
    int sum = 0;
    for (int i = 0; i < 3; i++) {
        sum += numbers[i];
    }
    return sum / 3;
}

The duplicated loop now exists once, and the two call sites read as what they mean. The extracted average still hardcodes the length 3 in both the loop bound and the divisor, so it silently only works for three-element arrays — numbers.length in both places is the obvious next step. Extracting the duplication and then generalising the extracted method is exactly the “short, deliberate steps” style above.

Feature envy

A method that spends most of its time reaching into another class’s data rather than its own. User.checkout() touches cart twice and User’s own state never — the logic is envious of ShoppingCart:

// Before
class ShoppingCart {
    public List<Item> getItems() {...}
    public int getVoucher() {...}
}

class User {
    private ShoppingCart cart;

    public double checkout() {
        double totalPrice = 0.0;
        for (Item item : cart.getItems()) {
            totalPrice += item.getPrice();
        }
        return totalPrice - cart.getVoucher();
    }
}
// After
class ShoppingCart {
    public List<Item> getItems() {...}
    public int getVoucher() {...}

    public double checkout() {
        double totalPrice = 0.0;
        for (Item item : getItems()) {
            totalPrice += item.getPrice();
        }
        return totalPrice - getVoucher();
    }
}

class User {
    private ShoppingCart cart;
}

Moving checkout() onto ShoppingCart turns two cross-class calls into two calls on this — the giveaway is that the cart. qualifier simply disappears:

Figure 98: Feature envy, before and after. Before: User.checkout() reaches across the class boundary into two of ShoppingCart’s members. After: checkout() sits with the data it uses, and User’s only link to ShoppingCart is the field it holds. Each box is a class with its members listed as ‘+ m()’. A solid arrow means ‘uses’ and points from the depender to the thing depended upon; it may land on an individual member row.

Two things improve at once: ShoppingCart gets more cohesive (the checkout logic now sits with the data it operates on) and User gets less coupled to it (one link instead of three). Both are the subject of java-cohesion-and-coupling.

Others

Many other code smells exist. Further reading:

  • Martin Fowler, Refactoring: Improving the Design of Existing Code (2nd edition, 2019)
  • Robert Martin, Clean Code: A Handbook of Agile Software Craftsmanship (2008)
  • John Ousterhout, A Philosophy of Software Design (2018)
  • and the catalog of refactorings at refactoring.com.

Java SOLID Principles

Introduced in 2026-04-02-refactoring (Lecture, Week 6, Part 3 — Single Responsibility and Open-Closed) and continued in 2026-04-16-solid-principles-ii (Lecture, Week 7 — Liskov Substitution, Interface Segregation, Dependency Inversion).

Why SOLID?

Large software tends to become:

  • Rigid — difficult to change; even small changes require modifications across many parts of the codebase.
  • Fragile — likely to break when changed, sometimes in parts of the codebase that appear unrelated to the change.

The SOLID principles (S-ingle responsibility, O-pen-closed, L-iskov substitution, I-nterface segregation, D-ependency inversion) are a set of guidelines — not rules — to help prevent rigidity and fragility. Many of the individual ideas predate the acronym; Robert Martin combined them in Design Principles and Design Patterns (2000).

Week 6 covers the first two: Single Responsibility and Open-closed.

Single Responsibility Principle (SRP)

There should never be more than one reason for a class to change.

Closely related to java-cohesion-and-coupling’s cohesion: cohesion is about how similar a class’s functionality is, while SRP is about the reasons for change. A “responsibility” is a reason for change — if you can think of more than one motive to change a class, it has more than one responsibility.

class Student {
    private String name;
    private List<Course> courses;
    private double gpa;

    public void enrollInCourse(Course course) { courses.add(course); }
    public void calculateGPA() { /* ... */ }
    public void printTranscript() { /* ... */ }
}

This class has three reasons to change:

  1. Changing how to enrol to courses.
  2. Changing how overall GPAs are calculated.
  3. Changing how transcripts are generated.

Splitting each concern into its own class gives each one a single responsibility:

class Student {
    private String name;
    private List<Course> courses;
    public void enrollInCourse(Course course) { courses.add(course); }
    public List<Course> getCourses() { return courses; }
}
class GPACalculator {
    public double calculateGPA(List<Course> courses) { /* ... */ }
}
class TranscriptPrinter {
    public void printTranscript(Student student) { /* ... */ }
}

Two details of the split are worth noticing. The gpa field is gone: it was a cached result of one of the three responsibilities, so it leaves with the responsibility, and GPACalculator.calculateGPA returns a value instead of assigning one. And Student gains getCourses(), because the two extracted classes now need the data from outside — the responsibilities separate cleanly, but they do not become independent.

The same shape, stated more briefly:

// Before                          // After
class Report {                     class ReportCalculator { }
    void calculateData() {}        class ReportSaver { }
    void saveToFile() {}           class ReportPrinter { }
    void printReport() {}
}

Calculating, saving and printing are three different reasons to change one Report class — a new output format, a new storage backend and a new formula are unrelated events — so they become three classes.

Homework. Check whether SRP improves memory management indirectly, by improving overall design structure — think about object creation, immutability (see java-mutability) and garbage collection.

Open-Closed Principle (OCP)

Components should be open for extension but closed for modification.

Introduced by Bertrand Meyer in Object Oriented Software Construction (1988): “if the open-closed principle is applied well, then further changes are achieved by adding new code, not by changing old code that already works”.

  • Open for extension — a class’s behaviour can be extended to support changing requirements.
  • Closed for modification — no one may change the behaviour of an existing class; it’s closed once it’s available for other modules to depend on.

A class is kept closed for modification by information hiding (see java-encapsulation).

Example: pluggable grading systems

The example picks up the GPACalculator extracted under SRP above, which assumes a single grading scheme:

class GPACalculator {
    public double calculateGPA(List<Course> courses) {
        double totalPoints = 0;
        for (Course course : courses) {
            totalPoints += course.getGradePoints();
        }
        return totalPoints / courses.size();
    }
}

Now a requirement arrives: the university needs to handle different grading systems, such as letter grades (A, B, C) and numerical grades (90, 80, 70). A first attempt branches on a gradeType string:

class GPACalculator {
    public double calculateGPA(List<Course> courses, String gradeType) {
        double totalPoints = 0;
        if (gradeType.equals("Letter")) {
            for (Course course : courses) {
                totalPoints += convertLetterGradeToPoints(course.getLetterGrade());
            }
        } else if (gradeType.equals("Numeric")) {
            for (Course course : courses) {
                totalPoints += course.getNumericGrade();
            }
        }
        return totalPoints / courses.size();
    }

    private double convertLetterGradeToPoints(String letterGrade) {
        // Convert letter grade to GPA points logic
        return 0;
    }
}

Three things carry the problem: the added String gradeType parameter, and the two string literals "Letter" and "Numeric". They are every place that has to be modified the next time a grading system is added, in a class that was supposed to be finished. The class is open for extension only by editing it, which is exactly what “closed for modification” forbids. (A gradeType string also reintroduces the Vehicle-style type switch from java-refactoring.)

Extracting the grading logic behind an interface makes GPACalculator open for extension (new GradingSystem implementations) without ever touching its own code again:

interface GradingSystem {
    double getGradePoints(Course course);
}
class LetterGradingSystem implements GradingSystem {
    @Override
    public double getGradePoints(Course course) { /* convert letter grade to points */ return 0; }
}
class NumericGradingSystem implements GradingSystem {
    @Override
    public double getGradePoints(Course course) { return course.getNumericGrade(); }
}

class GPACalculator {
    private GradingSystem gradingSystem;
    public GPACalculator(GradingSystem gradingSystem) { this.gradingSystem = gradingSystem; }

    public double calculateGPA(List<Course> courses) {
        double totalPoints = 0;
        for (Course course : courses) {
            totalPoints += gradingSystem.getGradePoints(course);
        }
        return totalPoints / courses.size();
    }
}

The caller picks the grading system and hands it to the calculator:

public static void main(String[] args) {
    List<Course> letterGradeCourses = new ArrayList<>();
    letterGradeCourses.add(new Course("CS", "A"));

    GradingSystem letterGradingSystem = new LetterGradingSystem();
    GPACalculator gpaCalculator = new GPACalculator(letterGradingSystem);
    System.out.println("GPA (Letter Grades): " + gpaCalculator.calculateGPA(letterGradeCourses));
}

Figure 99: The open-closed refactoring of GPACalculator. GPACalculator uses only the GradingSystem interface; each concrete grading system implements it. A new scheme — pass/fail, say — is a fourth box on the bottom row with a fourth dashed arrow, and no existing box changes: that is ‘open for extension, closed for modification’ as a picture. Each label carries the Java keyword and members are listed as ‘+ m()’. A solid line with a solid head means ‘uses’, a dashed line with an open head means ‘implements’, and every arrow points from the depender to the thing depended upon. This is not UML, which would draw realisation as a hollow triangle.

What the refactoring bought:

  • GPACalculator depends on the abstraction GradingSystem instead of calculating grade points itself — which makes it open for extension (new grading systems) but closed for modification.
  • More grading systems can be added without changing the core logic of GPACalculator.
  • The interface guarantees every grading system implements the same method (getGradePoints()), making it easy to switch between them.
  • main demonstrates using either LetterGradingSystem or NumericGradingSystem by passing a different grading system to the GPACalculator.

Two arrows into an abstraction that nobody edits is also how the class stays closed: the calculator is closed for modification because the only thing it can see of a grading system is the interface. That is information hiding used structurally, and it is the same move as the Dependency Inversion Principle below; the constructor parameter here is dependency injection.

Liskov Substitution Principle (LSP)

Subclasses should be substitutable for their parent classes.

Defined by Barbara Liskov in a 1987 keynote: an instance of a subclass type can be used wherever an instance of a superclass type is expected, without breaking the correctness of the program:

List<Animal> animals = new ArrayList<>();
animals.add(new Cat());
animals.add(new Mouse());
for (Animal animal : animals) {
    animal.eat(new Food());
}

Example violation

class Student {
    protected List<Course> courses;
    public double calculateGPA() {
        double totalPoints = 0;
        for (Course course : courses) {
            totalPoints += course.getGradePoints();
        }
        return totalPoints / courses.size();
    }
}
class PostgraduateStudent extends Student {
    @Override
    public double calculateGPA() {
        throw new UnsupportedOperationException("Postgraduates have a different GPA system.");
    }
}

Code written against Student (e.g. calling calculateGPA() on every student in a list) will blow up the moment a PostgraduateStudent is substituted in — PostgraduateStudent is not actually usable wherever a Student is expected, so it violates LSP.

Substitution with contracts

Even when a subclass overrides a method with a different implementation, it must still honour the parent’s contract (see java-specification):

class Parent {
    /**
     * @requires x > 0
     * @ensures \result > 'A' && \result < 'Z'
     */
    char f(int x);
}

Preconditions — suppose an overriding Child.f() can also handle negative numbers. Changing its precondition from x > 0 to x != 0 is fine: every input Parent.f() accepted (x > 0) is still accepted by Child.f() (x != 0), since \(x > 0 \Rightarrow x \neq 0\) — so the precondition became weaker (less strict), not stronger. Preconditions in a subclass must be no stronger than the superclass’s — they may be weaker or stay the same.

Postconditions — suppose Child.f() only ever returns 'K', 'L', or 'M'. A postcondition of \result > 'J' && \result < 'N' is fine: every result still satisfies the parent’s promise (\result > 'J' && \result < 'N' \Rightarrow \result > 'A' && \result < 'Z'), so the postcondition became stronger (more restrictive), which is allowed. Postconditions in a subclass must be no weaker than the superclass’s — they may be stronger or stay the same.

A subclass must not strengthen preconditions or weaken postconditions — it should accept everything the parent accepts, and still guarantee everything the parent guarantees.

Worked example

class One {
    /**
     * @require row != null && col != null && 0 < val && val < 100
     * @ensure \result is the list of all of the positive
     *     integers n < val that appear in either row or col
     */
    public List<Integer> calc(int[] row, int[] col, int val) { ... }
}
class Two extends One {
    /**
     * @require row != null && col != null && 0 < val &&
     *     val < 100 && row only contains positive integers
     * @ensure \result is the list of all of the positive
     *     integers n < val that appear in either row or col
     */
    @Override
    public List<Integer> calc(int[] row, int[] col, int val) { ... }
}

Two’s precondition adds an extra requirement (row only contains positive integers) that One never required — so One’s precondition does not imply Two’s: there are inputs One would accept (a row containing a negative number) that Two rejects. This strengthens the precondition and violates LSP: code written against One that happens to pass a negative-containing row would break if a Two were substituted in.

Homework variant: if Two’s postcondition is instead changed to return integers appearing in both row and col (rather than either), does this satisfy LSP? Reasoning it through: the guarantee changes from a union to an intersection, which for most inputs returns strictly fewer elements than One promised — that’s a weaker postcondition (some outputs a caller was guaranteed under One are no longer guaranteed under Two), which also violates LSP.

Interface Segregation Principle (ISP)

Many client-specific interfaces are better than one general-purpose interface.

Shrink interfaces to minimize incidental dependencies — large interfaces should be split into smaller ones, so implementing/using classes only need to be concerned about the methods that actually interest them.

class Z {
    public void a() {...}
    public void b() {...}
    public void c() {...}
    public void d() {...}
    public void e() {...}
}
// A only uses a() and b(), B only uses c(), C only uses d() and e() ...
// ...but all three classes still depend on the whole of Z.

This mirrors java-cohesion-and-coupling’s stamp coupling at the interface level: despite each client using only a small subset of Z, every client depends on all of Z — so a change to any part of Z risks affecting (and forcing a recompile/redeploy of) every client, even ones that never used the changed part. Splitting Z’s surface into focused interfaces removes those incidental dependencies:

interface AI { void a(); void b(); }
interface BI { void c(); }
interface CI { void d(); void e(); }
// Z implements AI, BI, CI; A depends only on AI, B only on BI, C only on CI.

Dependency Inversion Principle (DIP)

Depend upon abstractions. Do not depend upon concretions.

Entities must depend on abstractions, not concretions: high-level modules must not depend on low-level modules — both should depend on abstractions. If A depends directly on the concrete class B, changes to B’s implementation can propagate to A; if A instead depends only on an abstraction (BSpec) that B implements, changes inside B are far less likely to affect A, as long as BSpec itself stays the same.

Even a small step towards this helps — programming against the List interface instead of the concrete ArrayList type means Student no longer depends on which list implementation the caller chose:

class Student {
    private List<Course> courses; // not ArrayList<Course>
    public Student(List<Course> courses) { this.courses = courses; }
    public double calculateTotalGradePoints() { ... }
}

What makes a good dependency? (stability and exposure)

A class A has a dependency on class B if A refers to B in code (an import B;, or, in the same package, simply referring to B anywhere). Not all dependencies are equally risky — two properties determine how good/bad one is:

  • Stability — how likely the dependency is to change. ArrayList is a good dependency because it’s very unlikely to change; treat classes you write as unstable until proven otherwise, and generally assume interfaces are more stable than concrete classes (unless they’re poorly designed and change often).
  • Exposure — how much of the depending class is entangled with it. A dependency only used in a constructor is better than one used across every method, since less of the class would need to change if that dependency changed.

Two forms of DIP

Minimising concrete dependencies (the simple form) — change a field’s compile-time type from a concrete class to whatever interface it already implements, wherever one already exists:

- HardwoodFloor placedOn;
+ Floor placedOn;

This only helps where an abstraction already exists, though. The proper form of DIP goes further:

Remove dependencies on low-level components from high-level components — make both depend on an abstraction.

“High-level” vs “low-level” isn’t a strict distinction: high-level components implement application logic (e.g. a browser’s back/forward navigation history); low-level components do the grunt work that logic depends on (e.g. actually requesting a webpage’s data). The goal is for high-level components to talk to low-level ones exclusively through an abstraction, so a low-level component changing doesn’t force the high-level component depending on it to change too. Applied to a Desk class depending on a concrete LogitechKeyboard with no existing interface:

  1. Create an abstraction of the low-level component: interface Keyboard { void type(char key); ... }.
  2. Modify the low-level component to implement it: class LogitechKeyboard implements Keyboard.
  3. Minimise concrete dependencies in the high-level component: Keyboard keyboard = new LogitechKeyboard();.

Dependency Injection

Dependency Injection (DI) is a design pattern that implements DIP by injecting a class’s dependencies into it (e.g. via the constructor) instead of having the class create them internally, promoting loose coupling (see java-cohesion-and-coupling):

// Before: AlertService is tightly coupled to EmailSender, and creates its own dependency.
class AlertService {
    public void sendAlert(String msg) {
        EmailSender sender = new EmailSender();
        sender.send(msg);
    }
}
// After: AlertService depends on the MessageSender abstraction, injected via the constructor.
interface MessageSender {
    void send(String msg);
}
class EmailSender implements MessageSender {
    @Override
    public void send(String msg) { System.out.println("Sending EMAIL: " + msg); }
}
class SmsSender implements MessageSender {
    @Override
    public void send(String msg) { System.out.println("Sending SMS: " + msg); }
}
class AlertService {
    private MessageSender sender;
    public AlertService(MessageSender sender) { this.sender = sender; }
    public void sendAlert(String msg) { sender.send(msg); }
}

AlertService can now send alerts via email, SMS, or any future MessageSender implementation, without ever changing its own code.

A constructor isn’t the only injection point — a setter is appropriate when the dependency is likely to change over the object’s lifetime, e.g. public changeSender(MessageSender sender) { this.sender = sender; }. Eventually something (typically an entry-point method like main) has to construct the concrete dependencies before injecting them; DI frameworks let you defer that construction to runtime via the framework’s own configuration instead of in code, but unless a project needs multiple levels of injected dependencies, good design alone can avoid the extra conceptual overhead of adopting one.

Summary

  • Single Responsibility — one reason to change per class.
  • Open-Closed — open for extension, closed for modification.
  • Liskov Substitution — subclasses substitutable for their parents; no stronger preconditions, no weaker postconditions.
  • Interface Segregation — many small, client-specific interfaces beat one large general-purpose interface.
  • Dependency Inversion — depend on abstractions, not concretions; inject dependencies rather than constructing them internally.

Java Specification

Introduced in 2026-03-12-object-oriented-programming-ii (Lecture, Week 3). Extended in 2026-03-19-exceptions and formalised later in java-hoare-logic; pre/postconditions come back as class invariants in week8-tutorial-class-invariants and as the substitution principle in week9-tutorial-substitution-principle-and-pre-post-conditions.

The order below: Javadoc → restrictiveness → generality → formality → contracts → defensive programming.

Javadoc

  • Ordinary comments: // and /* ... */.
  • Javadoc comments:
    • begin with /** — note the second *; the Javadoc generator ignores all other comments;
    • end with */;
    • must sit immediately above the thing being documented;
    • use tags beginning with @;
    • some tags take parameters, some just text.

A worked example:

/**
 * Calculates a sum by combining the hash code of the provided string
 * and the long value of the provided float.
 *
 * @param inputString the input string whose hash code will be used
 * @param inputFloat  the float value to be converted to long and combined with the string hash code
 * @return a long value representing the sum of the string's hash code and the long value of the float
 */
public long doCalculation(String inputString, float inputFloat){
    long floatToLong = (long) inputFloat;

    // Combine the hash code of the string with the float-to-long value
    long result = inputString.hashCode() + floatToLong;

    return result;
}

Tags

Methods:

Tag Argument Meaning
@param varname … Describe a parameter for a method
@return … Describe the return value
@throws ExceptionType … Describe when a particular type of exception is thrown by the method
@requires Precondition Specify the assumptions for a method to execute properly
@ensures Postcondition Specify the effects of executing the method

Classes:

Tag Argument Meaning
@author authorname Specify the author of the class
@copyright … Provide details on who owns copyright
NoteThe contract tags are spelled two ways

The tag table above and the findMax example use @requires / @ensures. The formal withdraw specification and the contract examples use @require / @ensure, with no s. The same split runs across the course as a whole. Neither form is declared canonical, and the examples below use both. @requires and @ensures are not standard Javadoc tags. They are the course’s own convention layered on top of it, which is why the generator will not do anything special with them.

What makes a good specification

Ideally a specification will:

  • Allow the use of a method by only reading the specification, not by reading and understanding the implementation.
  • Allow a method to be re-implemented without requiring changes to any methods that use it.

And it should:

  • Rule out all implementations that are unacceptable — i.e. be sufficiently restrictive.
  • Not preclude acceptable implementations — i.e. be sufficiently general.
  • Be easy for users (programmers) to understand — i.e. be clear.

The next three sections take one method, search, and fail each of those three tests in turn.

Restrictiveness — keep out incorrect implementations

/**
 * Returns an index (i) of ar such that
 * ar[i] == x, if any.
 */
public int search(int[] ar, int x) {…}

This does not say what happens if x is not in ar. It is tempting to assume the obvious answer, but the specification doesn’t say, so don’t assume. By its silence, the specification allows any value to be returned. So a return of 1 or 0 could mean “It’s at index 1/0” or “I didn’t find it”.

Adding the missing case makes it better, still bad:

/**
 * Returns an index (i) of ar such that
 * ar[i] == x, if any
 * else, return -1
 */
public int search(int[] ar, int x) {…}

Suppose x appears in ar multiple times. There is nothing in the spec that requires:

  • that you will get the lowest index;
  • that you will get the same answer running multiple times.

The specification is non-deterministic.

Figure 100: With the spec worded as ‘returns an index i such that ar[i] == x’, both cells holding 3 are legal answers, and nothing forbids the method returning a different one on each call. That is what makes the specification non-deterministic.

Generality — allow acceptable alternative versions

The obvious fix for the non-determinism is to say which index you get. Saying it like this, however, is a bad example:

/**
 *  Examine ar[0], ar[1], ... in turn and
 *  return the index of the
 *  first one that is equal to x, if any,
 *  else return -1
 */
public int search(int[] ar, int x) {…}

It is restrictive enough, but it over-commits: it describes how the method walks the array. A forward-scanning implementation goes with it (see the warning below before trusting this listing):

public int search(int[] ar, int x) {
    int found = -1;
    for (int i = 0; i < ar.length; i++) {
        if (ar[i] == x) {
            found = i;
        }
    }
    return found;
}

The consequence of the over-committed wording shows when the loop is run the other way:

public int search(int[] ar, int x) {
    int found = -1;
    for (int i = ar.length-1; i >= 0; i--) {
        if (ar[i] == x) {
            found = i;
        }
    }
    return found;
}

Scanning backwards and keeping the last match found is the smallest matching index — the answer the spec asks for — but the specification said ar[0], ar[1], ... in turn, so this version does not satisfy the specification. A perfectly good implementation has been outlawed by wording that was never about the outcome.

Even if you think that is the most natural way to do something, that doesn’t mean it should be part of the specification.

Specs should describe what happens, not how.

Rewritten to talk about the result only, the specification now accepts the backward implementation:

/**
 * Return smallest index (i) of ar such that
 * ar[i] == x, if any,
 * else return -1
 */
public int search(int[] ar, int x) {…}
WarningThe forward listing does not return the smallest index

The backward scan above returns the smallest index, so it satisfies the rewritten spec. The forward scan from earlier does not:

for (int i = 0; i < ar.length; i++) {
    if (ar[i] == x) { found = i; }
}
return found;

That loop overwrites found on every match, so it returns the largest matching index, not the smallest — and not the first one either, which is what the earlier spec asked for. On ar = [1,3,4,2,3,5] with x = 3 it returns 4 where both specs want 1. The forward and backward listings only agree when x occurs at most once. A forward scan that satisfies the spec has to stop at the first match:

for (int i = 0; i < ar.length; i++) {
    if (ar[i] == x) { return i; }
}
return -1;

Clarity

  • A specification should facilitate communication between people.
  • Two ways in which communication could fail:
    • the reader doesn’t understand;
    • the reader only thinks they understand.
  • Clarity can be improved by being as concise as possible. Long specs are:
    • more likely to contain errors/contradictions,
    • less likely to be read properly,
    • more likely to be misunderstood.
  • Redundancy may help — but be clear that it is redundant, by using e.g. “e.g.” or “i.e.”.

Four specs to judge

Four one-line specifications. The question for each is whether it is a good specification.

/**
 * Sorts the given array.
 */
public void sort(int[] ar) {...}
/**
 * Calculate x to the power of two with Math.pow.
 */
public int square(int x) {...}
/**
 * Returns the list of ResourceContainers stored by this instance.
 */
public List<ResourceContainer> getResources() {...}
/**
 * Calculate the nth value of the fibonacci sequence.
 */
public long fib(int n) {...}

Applying the three criteria (restrictive, general, clear):

  • sort — under-restrictive. Ascending or descending? In place, or is the return of void supposed to imply in place? What about equal elements?
  • square — over-general in one direction and over-specific in another: it names Math.pow, which is a how, exactly the generality failure above; and it never says what happens on overflow.
  • getResources — the mutability trap from java-mutability. Is the returned List the instance’s own list, so that the caller can add to it, or a copy? Restrictiveness: the spec’s silence permits either, so no caller can safely do anything with it.
  • fib — under-restrictive on the domain and on the indexing convention. Is fib(0) 0 or 1? What happens for negative n, or for an n whose answer overflows long?

Formality

Specifications of software range in formality:

  • informal — e.g. normal comments;
  • semi-formal — structured English documentation, e.g. using Javadoc tags;
  • formal — mathematical constraints, e.g. using Java syntax for boolean expressions.

Here is the same method specified three times, once at each level.

Informal:

/**
 * Withdraws an amount from this account and
 * returns how much is left.
 */
public int withdraw(int amount) {...}

This leaves three things open: what happens when amount is negative, what happens when amount is bigger than the balance, and whether the balance is changed when there is a failure.

Semi-formal — structured English, one tag per obligation:

/**
 * Withdraw an amount from this account.
 *
 * @param amount the amount to withdraw, must be a positive integer.
 * @return the new balance after the withdrawal.
 * @throws IllegalArgumentException if the amount is negative.
 * @throws InsufficientFundsException if the amount is greater than the current balance.
 */
public int withdraw(int amount) {...}

Formal — boolean expressions in Java syntax, with \old(...) naming the value an expression had before the call:

/**
 * Withdraws an amount from this account.
 *
 * @require amount >= 0
 * @require amount <= getBalance()
 * @ensure getBalance() == \old(getBalance()) - amount
 */
public int withdraw(int amount) {...}

There is no @throws in the formal version. The failure cases have not been forgotten: they have been moved into the caller’s obligations. The next section covers this.

Contracts

Specifications can be written using contracts:

/**
 * [Description of method's behaviour]
 *
 * @require [Precondition]
 * @ensure [Postcondition]
 */
  • If the code calling the method satisfies the precondition, then the method guarantees to satisfy the postcondition.
  • If the code calling the method does not satisfy the precondition, then the method guarantees nothing — any behaviour is allowed.

Programming with contracts

\result names the returned value inside a postcondition:

/**
 * Withdraws an amount from this account.
 *
 * @require amount >= 0
 * @require amount <= getBalance()
 * @ensure getBalance == \old(getBalance()) - amount
 * @ensure \result == getBalance()
 */
public int withdraw(int amount) {
    // no need to check the conditions
}
int balance = myAccount.withdraw(amt);

In the first @ensure, getBalance is written without the parentheses it has in the formal specification above.

It is up to the calling code to make sure it fulfils its side of the contract, i.e. 0 <= amt <= myAccount.getBalance().

The method body carries no validation at all, and the call site carries no error handling — the postcondition is unconditional, so balance is always meaningful.

Programming without contracts

The same method written defensively instead, with the failure folded into the return value:

/**
 * Withdraw an amount from this account.
 *
 * @param amount The amount to withdraw.
 * @return The balance of this account after
 *         the withdrawal successfully occurs,
 *         or -1 if it fails.
 */
public int withdraw(int amount) {
    if (amount < 0) {
        return -1;
    }
    if (balance < amount) {
        return -1;
    }
}
int balance = myAccount.withdraw(amt);
If(balance == -1) {
   ...
}

The method body shows only the two checks; the success path is left out. The call site writes If with a capital where Java needs if.

The cost is visible on both sides: the method now checks twice on every call, and every call site has to branch on a sentinel. It also re-introduces exactly the restrictiveness problem from search — -1 has to mean both “a balance” and “it failed”.

Defensive programming

Definition (Defensive Programming) Explicitly checking for invalid inputs and bad situations, ensuring the software does not behave dangerously regardless of input.

Sooner or later someone will call the method without checking the precondition. Particularly when dealing with external input sources or when guarding critical resources, it may be better to be defensive outside the wall and use contracts inside it.

Figure 101: Defensive outside the wall, contracts inside it: validate defensively where untrusted input crosses into the system, and rely on contracts for the internal calls behind that boundary, so the check happens once rather than at every hop. The gate box is the findMax method worked through below.

Worked example: findMax

The starting point, with no specification and no checks:

public int findMax(int[] numbers) {
    int max = Integer.MIN_VALUE;
    for (int i = 0; i < numbers.length-1; i++) {
        if (numbers[i] > max) {
            max = numbers[i];
        }
    }
    return max;
}

Documented, and with the defensive check added:

/**
 * Finds the maximum value in the given array of integers.
 *
 * @param numbers An array of integers from which the maximum value is to be found.
 * @return The maximum value in the array.
 * @throws IllegalArgumentException if the array is null or empty.
 *
 * @requires numbers != null && numbers.length > 0
 *    - The array must not be null.
 *    - The array must contain at least one element.
 *
 * @ensures
 *    - The method returns the maximum value found in the array.
 *
 */
public int findMax(int[] numbers) {
    if (numbers == null || numbers.length == 0) {
        throw new IllegalArgumentException("Array must not be null or empty.");
    }

    int max = Integer.MIN_VALUE;
    for (int i = 0; i < numbers.length; i++) {
        if (numbers[i] > max) {
            max = numbers[i];
        }
    }
    return max;
}

This version writes the precondition down as @requires, promises an exception in @throws for callers who break it anyway, and then checks it in the body — belt and braces, which is the whole point of being defensive at a boundary. Without the check, a null array throws NullPointerException and an empty array silently returns Integer.MIN_VALUE as if that were a real maximum.

TipThe loop bound differs between the two versions

The first version loops i < numbers.length-1 and the documented version loops i < numbers.length. The first version therefore never examines the last element, so findMax(new int[]{1, 2, 9}) returns 2. No specification was attached to the first version, so nothing about it was wrong according to its spec, because it did not have one.

Further reading

Key takeaways

  • A specification describes the contract between a method and its client.
  • It explains what the method does, not how it is implemented.
  • A good specification clearly states:
    • Preconditions — conditions that must be true before the method is called;
    • Postconditions — conditions that will be true after the method finishes successfully;
    • Side effects — any additional changes the method makes to the system.
  • Clear specifications make code easier to understand, use, and maintain.

Java Testing

Introduced in 2026-03-26-testing (Lecture, Week 5).

Levels of testing

  1. Unit testing — check that each “unit” in the project behaves correctly.
  2. Integration testing — check that components work together and that the interfaces between components work as expected.
  3. System testing — does the system as a whole work correctly?
  4. (User) acceptance testing — do users of the system agree that the system does what it’s supposed to do?

Figure 102: The four levels of testing as a pyramid. Unit tests form the wide base, acceptance tests the narrow apex. In the usual test-pyramid reading, the width of a band stands for how many tests of that kind a project has.

Test frameworks

Libraries that make writing and running tests easier. xUnit is the prevalent family — JUnit, NUnit, CPPUnit, PyUnit, … — and this course uses JUnit 4 (http://junit.org/junit4); see java-junit.

Depending on how the software is structured, a unit-testing framework can also be driven for other kinds of automated testing. A caveat: “unit testing” is sometimes incorrectly used to mean any automated test.

Regression testing

During development, testing helps answer (at least) two questions:

  • Does the new stuff work?
  • Have we broken things which used to work — have we regressed?

Regression testing ensures that old features are still working as they should when new features are introduced.

Figure 103: A regression (chart after browserstack.com/guide/regression-testing). Nine bars on Tests/Time axes: read each bar as a build, and its height as the size of the test suite growing as features are added. The red top slice on the second-to-last bar is the regression, and the arrow labelled Bug! points at it.

Black box vs white/glass box testing

  • Black box — the software has inputs and outputs to test, but the implementation is unknown to you; you test according to the specification (see java-specification) — what it’s supposed to do.
  • White/glass box — testing designed with knowledge of the internal implementation, so tests can pay special attention to cases where the implementation is complicated.

Figure 104: The two testing stances. Both are the same grey cube. The black box is opaque and shows only its input and output arrows. The glass box is translucent, so the implementation inside, a recursive fib, can be seen through its walls.

Black box techniques

Black box testing works from the Javadoc alone. The running example is a bus, and the specification is all you get:

/**
 * Calculate how many passengers are currently on the bus.
 *
 * @returns The number of passengers on the bus.
 */
public int getCurrentPassengers() {...}

/**
 * Calculate the average number of passengers on the bus between stops.
 *
 * @returns The average passengers on the bus.
 */
public int getAverageCount() {...}
Note

The tag is written @returns here and @return in the specification tag table from the exceptions lecture. The course uses both spellings — see csse2002-diagram-notation, “Specification tag spelling”.

Smoke tests — test the common-case functionality. Usually the first test to be performed (“can it run?”), used to determine whether further, more rigorous testing is required. The name comes from electronic hardware testing: plug in a new board, turn on the power, and if you see smoke coming from the board, turn the power off — you don’t have to do any more testing. (From Lessons Learned in Software Testing.)

Boundary tests — investigate extremes and corner cases, i.e. where bugs often occur:

Input type Try
Whole number 0, -1, minimum value, maximum value
Floating point 0, -1, NaN, infinity
Collection (array, list, set, etc.) empty, one element, large
Reference type null
Resource (file, link) non-existent resource

Equivalence classes — groups of inputs that the system treats the same way. For getCurrentPassengers() on a bus whose maximum capacity is 80, build the table in two passes: first the classes, then the boundary tests for each class.

Class Values Boundary tests
Valid – Empty 0 -1, 0, 1
Valid – Normal 1 – 79 (any number within the range) Covered by above and below
Valid – Full capacity 80 79, 80, 81
Invalid – -1, 81

Minimal boundary set: -1, 0, 1, 79, 80, 81. The “Normal” class contributes no probes of its own because its edges are already the outer probes of the classes on either side.

The black-box method

The method in six points:

  1. Black box testing: no knowledge of implementation, only specification.
  2. JUnit is a test framework.
  3. Tests must not violate preconditions.
  4. Start with smoke tests.
  5. Expand test suite with boundary tests.
  6. Stop when confidence is high.

Point 3: a test that breaks @requires proves nothing, because the method is free to do anything at all once its precondition is violated. Point 6: testing is never exhaustive, so you stop on judgement rather than on a completeness proof. The loop argument below makes the same admission concrete.

White box technique: code coverage

With tests and an implementation, code coverage measures how much of the code is actually tested: of all the different ways your program could run, how many are covered by your tests. There are three levels, in this order:

  1. Statement coverage — each statement is executed.
  2. Branch coverage — each branch is tested for the true case and the false case.
  3. Path coverage — every ‘path’ through the code is traversed.

A worked example:

public void register(int x) {
    if (x > 0) {
        positives += 1;
    }
    if (x % 2 == 0) {
        evens += 1;
    }
}
  • Statement coverage: any odd positive value, e.g. x = 1, gives a partial run: if (x > 0), positives += 1 and the if (x % 2 == 0) test are executed while evens += 1 is missed. x = 2 alone executes every statement, since it is positive and even so both if bodies run.
  • Branch coverage: x = 2 makes both conditions true and x = -1 makes both false, so x = 2 and x = -1 together give each condition both outcomes, true, false. Two tests.
  • Path coverage: all four combinations of the two conditions, so four tests. The four inputs are in the table below.

Figure 105: Path coverage for register. Each internal box is a condition, each teal arrow an outcome labelled true/false, each leaf one complete path to exit — four leaves, so four tests. The magenta input under each leaf is a value of x that drives that path.

Written out, the four paths and their inputs are:

Path x
x > 0 && x % 2 == 0 2
x > 0 && !(x % 2 == 0) 1
!(x > 0) && x % 2 == 0 -2
!(x > 0) && !(x % 2 == 0) -1

The three levels run from weakest to strongest, and this exercise makes that concrete: the same x = 2 that gives full statement coverage misses three of the four paths. That is why “100% statement coverage” is a weak claim.

Loops make exhaustive path coverage infeasible
for (int i = 0; i < 100; i++) {
    if (f(i, k)) {
        j++;
    }
}

There are \(2^{100}\) paths through this program — 1,267,650,600,228,229,401,496,703,205,376 of them. At a billion tests per second that is 40.2 trillion years, roughly 2900 times the age of the universe.

So path coverage is approximated. The common approximation is that 2 or more iterations through a loop, or recursive calls, are equivalent. This is engineers’ induction: “One, two, three — that’s good enough for me.” For for (init; test; iterate) { body } the three cases to test are:

  • 0 iterations: init; test (fails); nextStatement;
  • 1 iteration: init; test; body; iterate; test (fails); nextStatement;
  • 2 iterations: init; test; body; iterate; test; body; iterate; test (fails); nextStatement;
Using JUnit for white-box testing

Design tests based on internal logic. You try to cover branches, loops and edge cases, and you may aim for a code coverage target (e.g. 100%). A worked white-box example — DiscountCalculator, the five tests that cover it, and its branch tree — is in java-junit.

Test Driven Development (TDD)

The TDD approach originates from the Agile manifesto principles and Extreme Programming. In TDD, developers create small test cases for every feature based on their initial understanding. The primary intention is to modify or write new code only if the tests fail — this prevents duplication of test scripts. Use the tests to determine when code is “ready”.

Figure 106: The TDD cycle. Read it counter-clockwise: write a test, watch it fail (pink), write code, watch it pass (green), refactor, and go round again. The teal arrow on the right points at Write Test and marks the entry point of the loop: the test comes before the code.

The Refactor step connects to java-refactoring: the green test suite is what makes it safe to restructure code without changing its behaviour.

Version Control

A Week 4 supplementary topic, and the only one in the course that isn’t about Java. Not examinable (confirmed in 2026-05-28-course-summary-and-exam-preparation) — but it’s the piece of the course you’ll use every day afterwards.

Why

Software changes frequently, and version control preserves the history of those changes. The everyday shape of the thing is a word processor’s version-history sidebar: a list of edits, each entry timestamped and attributed to a named collaborator, with a Restore this version button.

The alternative most students reach for — copying files into another directory — is incredibly error prone. It ends up as a folder of Super Cool Report v1.xlsx … v3.1 … v4a … v4b … vFinal … vFinal_1 … vFinal_Final … vFinal_Final-UPDATED_NEW.xlsx, or a set of directories running project-v0.1 through project-v2.3 with a project-v2.1-backup wedged in the middle.

In real development we want three things that copying can’t give us:

  1. To work on our own version and send changes back (commit) when they work. We don’t want everyone editing the same code in real time; the software would rarely compile while others were working on it.
  2. Labelled changes — a record of what changed and why, so bad changes are easy to find and undo. Changes frequently introduce new bugs.
  3. To work with any text files, not just source.

What a VCS does

A version control system tracks a folder and its contents, the history of changes within it, and metadata about that history (when a change was made, and by whom). History is recorded as snapshots — the entire contents of the folder at one point in time.

Benefits in this course:

  • Inspect old versions of your code — “this was working before!”
  • Identify what you changed recently — and remember, be suspicious of recently changed code when debugging (see week5-lab-debugging).
  • Practice for your future career.

Terminology

Term Meaning
Version control Tracking the history of changes such that old versions can be restored
Repository A folder placed under version control
Commit A snapshot of a repository at a point in time
History A list of commits in a repository

By market share: Git 93.87%, Subversion 5.17%, none 4.31%, Mercurial 1.13%.

When to commit

Commit when you create something that works, or fix something that was broken.

Commit Do not commit
Finished the dependencies method of addCustomer It’s 5 o’clock
Fixed the code style of AddressBook Changing to a new computer
Fixed a bug in Farm.core Completed the assignment
Fixed a typo in the description of the update method

The pattern: the left column describes a change to the code; the right column describes something that happened to you. A commit message should be about the former.

The staging area

To prepare a commit you add your changes to the staging area — the middle ground between what you have done to your files (the working directory) and what you last committed.

Figure 107: The three places a change can be, and the one command that moves it between each pair. This is the whole reason the staging area is a separate idea: git add does not save anything permanently and git commit does not look at your files, it looks at what you staged.

What should be committed?

Not everything in a folder belongs in version control. A repository should contain everything required to build or run the project, and not more.

  • Beware generated files — if you don’t edit the file, don’t commit it.
  • Beware proprietary formats like PowerPoint or Word documents — if your file is not plain text, consider leaving it out.
  • Tell Git what to skip with a .gitignore.

Common commands

Command Does
git init Create a new Git repository
git add Add working changes to the staging area
git commit Commit the changes in the staging area
git log View the repository history
git diff View working changes

Remotes — and a warning

A repository can be stored on a remote site; popular ones are GitHub, GitLab and BitBucket. An account with a lot of contributions can look good on a resume, but the rule that matters here is:

Do not make assessment public on these websites.

Publishing coursework counts as showing your code, which csse2002 lists explicitly under misconduct.

Further learning

Git is a powerful tool you’ll use extensively, and there is much more to it than the above. To go further, use the Git edX courses (accessible with a UQ student account) and the Atlassian Git tutorials.