Luleå University of Technology

LTU courses · Object-Oriented Programming in Java

Course D0010E

Advanced programming in Java: object-oriented design, algorithms, data structures, and software engineering. Labs added progressively as the course continues.

Java OOP Algorithms Data Structures Lab 1 of many

Lab 1: Arithmetic Quiz & Spellchecker

Two programs, one launcher

Main.java presents a menu to launch either the Arithmetic quiz or the Spellchecker. Both are fully interactive. Try them live below.

Lab 1 · Part A
Arithmetic quiz

10 random questions covering +, −, ×, ÷. First correct answer earns 10 points, second attempt earns 5. Max score: 100.

ArithmeticProblem.java ArithmeticQuiz.java Random Scoring
Live Demo

10 questions, random operators. Answer correctly first try for 10 pts, second try for 5 pts.

ArithmeticProblem.java
public class ArithmeticProblem {
    private final int operand1, operand2;
    private final char operator;

    public ArithmeticProblem(char op) {
        if (op != '+' && op != '-' && op != '*' && op != '/')
            throw new IllegalArgumentException("Operator is not legal.");
        operator = op;
        switch (operator) {
            case '+':
                operand1 = (int)(101 * Math.random());
                operand2 = (int)((101 - operand1) * Math.random());
                break;
            case '-':
                operand1 = 9 + (int)(92 * Math.random());
                operand2 = (int)((1 + operand1) * Math.random());
                break;
            case '*':
                operand1 = (int)(51 * Math.random());
                operand2 = (int)(13 * Math.random());
                break;
            default: // '/'
                int answer = (int)(13 * Math.random());
                operand2 = 1 + (int)(12 * Math.random());
                operand1 = operand2 * answer;
                break;
        }
    }

    public String getQuestion() {
        return String.format("What is %d %s %d ?", operand1, operator, operand2);
    }

    public int getAnswer() {
        switch (operator) {
            case '+': return operand1 + operand2;
            case '-': return operand1 - operand2;
            case '*': return operand1 * operand2;
            default:  return operand1 / operand2;
        }
    }
}
Lab 1 · Part B
Spellchecker

Checks words against a 72,875-word dictionary. If misspelled, suggests corrections using five different algorithms.

Spellcheck.java WordList.java 5 algorithms 72,875 words
Live Demo Loading dictionary…
Try:
Spellcheck.java
public class Spellcheck {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        WordList wordList = new WordList();
        System.out.println("Word list contains " + wordList.size() + " words.");

        while (true) {
            System.out.print("Enter a word (or 'exit'): ");
            String input = in.nextLine().trim().toLowerCase();
            if (input.equals("exit")) break;

            if (wordList.contains(input))
                System.out.println("'" + input + "' is spelled correctly.");
            else {
                System.out.println("'" + input + "' is NOT spelled correctly.");
                System.out.println("Did you mean:");
                delete_suggestion(input, wordList);
                insert_suggestion(input, wordList);
                swap_suggestion(input, wordList);
                swap_suggestion2(input, wordList);
                insert_space_suggestion(input, wordList);
            }
        }
    }

    // Delete one character at each position
    static void delete_suggestion(String input, WordList wl) {
        for (int i = 0; i < input.length(); i++) {
            String s = input.substring(0,i) + input.substring(i+1);
            if (wl.contains(s)) System.out.println("  - " + s);
        }
    }

    // Insert every letter at every position
    static void insert_suggestion(String input, WordList wl) {
        for (char c = 'a'; c <= 'z'; c++)
            for (int i = 0; i <= input.length(); i++) {
                String s = input.substring(0,i) + c + input.substring(i);
                if (wl.contains(s)) System.out.println("  - " + s);
            }
    }

    // Replace each character with every other letter
    static void swap_suggestion(String input, WordList wl) {
        for (int i = 0; i < input.length(); i++)
            for (char c = 'a'; c <= 'z'; c++) {
                if (c == input.charAt(i)) continue;
                String s = input.substring(0,i) + c + input.substring(i+1);
                if (wl.contains(s)) System.out.println("  - " + s);
            }
    }

    // Swap adjacent characters
    static void swap_suggestion2(String input, WordList wl) {
        for (int i = 0; i < input.length() - 1; i++) {
            char[] arr = input.toCharArray();
            char tmp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = tmp;
            String s = new String(arr);
            if (wl.contains(s)) System.out.println("  - " + s);
        }
    }

    // Split into two valid words
    static void insert_space_suggestion(String input, WordList wl) {
        for (int i = 1; i < input.length(); i++) {
            String a = input.substring(0,i), b = input.substring(i);
            if (wl.contains(a) && wl.contains(b))
                System.out.println("  - " + a + " " + b);
        }
    }
}
Lab 2: Custom ArrayList Implementation

Building ArrayList from scratch

MyArrayList<E> is a generic, resizable array list built to match Java's real ArrayList API without using it. Implements List<E>, Cloneable, Serializable, and RandomAccess. All 15 unit tests in MyArrayListTest.java pass.

§1: Basic info size() isEmpty() clear()
§2: Capacity ensureCapacity() trimToSize()
§3: Add add(index, e) add(e)
§4: Read get(index) set(index, e)
§5: Remove remove(index) removeRange(from, to)
§6: Search indexOf(o) remove(o) contains(o)
§7: Copy clone() toArray()
Lab 2 · MyArrayList<E>
Generic resizable array list ★ Live demo

Try the full implementation live: add, get, set, remove, indexOf, contains, clone, and more. Internally uses a dynamic array that doubles in size when full, exactly like the real Java ArrayList.

Generic <E> Dynamic array O(1) amortized add O(n) insert/remove Shallow clone
Live Demo: MyArrayList<Integer>
Array state size: 0 · capacity: 10
List is empty. Add some elements.
MyArrayList ready. Select an operation above.
list>
MyArrayList.java
public class MyArrayList<E> implements List<E>, Cloneable, Serializable, RandomAccess {

    private E[] array;
    private int size;
    private static final int DEFAULT_CAPACITY = 10;

    // ── CONSTRUCTORS ──────────────────────────────────────────
    public MyArrayList(int initialCapacity) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
        array = (E[]) new Object[initialCapacity];
        size = 0;
    }

    public MyArrayList() { this(DEFAULT_CAPACITY); }

    // ── §1: BASIC INFO ────────────────────────────────────────
    public int size()      { return size; }
    public boolean isEmpty() { return size == 0; }

    public void clear() {
        for (int i = 0; i < size; i++) array[i] = null;
        size = 0;
    }

    // ── §2: CAPACITY ──────────────────────────────────────────
    public void ensureCapacity(int minCapacity) {
        if (minCapacity > array.length) {
            int newCap = Math.max(array.length * 2 + 1, minCapacity);
            E[] newArr = (E[]) new Object[newCap];
            for (int i = 0; i < size; i++) newArr[i] = array[i];
            array = newArr;
        }
    }

    public void trimToSize() {
        if (size < array.length) {
            E[] newArr = (E[]) new Object[size];
            for (int i = 0; i < size; i++) newArr[i] = array[i];
            array = newArr;
        }
    }

    // ── §3: ADD ───────────────────────────────────────────────
    public void add(int index, E element) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        ensureCapacity(size + 1);
        for (int i = size; i > index; i--) array[i] = array[i - 1];
        array[index] = element;
        size++;
    }

    public boolean add(E e) { add(size, e); return true; }

    // ── §4: READ / REPLACE ────────────────────────────────────
    public E get(int index) {
        if (index < 0 || index >= size)
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        return array[index];
    }

    public E set(int index, E element) {
        if (index < 0 || index >= size)
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        E old = array[index];
        array[index] = element;
        return old;
    }

    // ── §5: REMOVE ────────────────────────────────────────────
    public E remove(int index) {
        if (index < 0 || index >= size)
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        E removed = array[index];
        removeRange(index, index + 1);
        return removed;
    }

    protected void removeRange(int fromIndex, int toIndex) {
        if (fromIndex < 0 || toIndex > size || fromIndex > toIndex)
            throw new IndexOutOfBoundsException();
        int count = toIndex - fromIndex;
        for (int i = toIndex; i < size; i++) array[i - count] = array[i];
        for (int i = size - count; i < size; i++) array[i] = null;
        size -= count;
    }

    // ── §6: SEARCH ────────────────────────────────────────────
    public int indexOf(Object o) {
        for (int i = 0; i < size; i++)
            if (o == null ? array[i] == null : o.equals(array[i])) return i;
        return -1;
    }

    public boolean remove(Object o) {
        int idx = indexOf(o);
        if (idx == -1) return false;
        remove(idx);
        return true;
    }

    public boolean contains(Object o) { return indexOf(o) != -1; }

    // ── §7: COPY ──────────────────────────────────────────────
    public Object clone() {
        MyArrayList<E> copy = new MyArrayList<>(size);
        for (int i = 0; i < size; i++) copy.array[i] = array[i];
        copy.size = this.size;
        return copy;
    }

    public Object[] toArray() {
        Object[] out = new Object[size];
        for (int i = 0; i < size; i++) out[i] = array[i];
        return out;
    }
}
Lab 3: Room Navigation Game (MVC + Observer)

A Swing game with full MVC architecture

Navigate between coloured rooms connected by corridors using WASD keys. Built with clean MVC: Nivå (model) extends Observable, Målarduk (view) renders on a JPanel, Tangentbordslyssnare (controller) handles keyboard input, and GUI implements Observer to repaint on every move. The canvas below is a pixel-accurate recreation of the actual Java Swing game.

Model
NivåObservable
RumRoom data
GångCorridor
VäderstreckEnum N/E/S/W
View
GUIJFrame + Observer
MålardukJPanel painter
Controller
Tangentbords­lyssnareKeyListener WASD
Utilities
GrafikDraw helpers
PunktImmutable point
GlobalaKonstanterShared constants
Lab 3 · Rumnavigering
Room Navigation Game ★ Live Demo

Exact map from Huvudprogram.java, 8 rooms, 10 corridors. Click the map then use WASD to navigate. Black dot = your position.

MVCObserver pattern Java Swing8 rooms 10 corridorsWASD
Live Demo: Exact Java Swing Recreation

Click the canvas to focus it, then use WASD to move between rooms.

Current room: Orange
Edit Rooms
Corridor
Background
Colour Name W × H X , Y
GUI.java
public class GUI extends JFrame implements Observer {
    private Målarduk målarduk;

    public GUI(Nivå enNivå) {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        enNivå.addObserver(this); // register so we repaint on level change

        målarduk = new Målarduk(enNivå);
        målarduk.setPreferredSize(new Dimension(800, 600));
        målarduk.addKeyListener(new Tangentbordslyssnare(enNivå));

        setContentPane(målarduk);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        målarduk.requestFocusInWindow();
    }

    @Override
    public void update(Observable o, Object arg) {
        this.målarduk.repaint(); // called whenever Nivå.notifyObservers() fires
    }
}
>
Lab 4: FIFO Queue & Breadth-First Traversal

Two data structures working together

FIFO.java implements a circular-buffer queue. GraphIO.java reads a graph from a file. The BFS algorithm uses the FIFO queue to visit every node in the graph level by level, nearest nodes first. Click any node below to watch BFS spread outward, and see the queue state at each step.

1
Pick a start
Add your chosen node to the queue. Mark it so we don't visit it twice.
→
2
Spread outward
Take the front node out of the queue. Add all its unvisited neighbours to the back.
→
3
Keep going
Repeat step 2 until the queue is empty. Every node gets visited exactly once, closest first.
Lab 4 · BFS on a Grid Graph
Breadth-first traversal ★ Live demo

Click any node to start BFS from there. Watch it sweep outward level by level. The FIFO queue state is shown live, each level gets a new colour. Switch between the two graph files from class.

FIFO.java GraphIO.java Circular buffer BFS Grid graph
Live Demo

Click any dot on the graph to start, or just hit Step or Run to pick a random start automatically.

FIFO queue
Queue empty, click a node to start
BFS Log
Select a start node...
Progress
0 / 0 visited
FIFO.java
public class FIFO implements Queue {
    private Object[] data;
    private int size, front, back;

    public FIFO(int capacity) {
        data  = new Object[capacity];
        size  = 0; front = 0; back = 0;
    }

    public int size()    { return size; }
    public boolean isEmpty() { return size == 0; }
    public int maxSize() { return data.length; }

    public Object first() {
        if (isEmpty()) throw new NoSuchElementException("Queue is empty");
        return data[front];
    }

    // Circular buffer: wrap index with modulo instead of shifting elements
    public void removeFirst() {
        if (isEmpty()) throw new NoSuchElementException("Queue is empty");
        data[front] = null;
        front = (front + 1) % data.length; // wrap around
        size--;
    }

    public void add(Object o) {
        if (size == data.length) throw new IllegalStateException("Queue is full");
        data[back] = o;
        back = (back + 1) % data.length;   // wrap around
        size++;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof FIFO)) return false;
        FIFO other = (FIFO) obj;
        if (this.size != other.size) return false;
        for (int i = 0; i < size; i++) {
            Object a = this.data[(front + i) % data.length];
            Object b = other.data[(other.front + i) % other.data.length];
            if (a == null ? b != null : !a.equals(b)) return false;
        }
        return true;
    }
}
Lab 5: Calculator (State Machine + OOP)

A state machine disguised as a calculator

The calculator is built around four states: Input1 → OpReady → Input2 → HasResult. Each button type is its own class extending the abstract CalculatorButton, and each implements a transition() method that changes the state. The Situation object holds all shared state: display, operands, current operator.

Input1 Entering first number
→ op →
OpReady Operator chosen, waiting for second number
→ digit →
Input2 Entering second number
→ = →
HasResult Result shown, ready for next calculation
Lab 5 · Calculator
Integer calculator ★ Live demo

Fully functional calculator, exact port of the Java Swing version. The current state is shown live so you can see the state machine in action as you type.

State machine Abstract class Polymorphism Java Swing OOP
Live Demo
0
State Machine Inspector
Input1
OpReady
Input2
HasResult
Left operand 0
Operator —
Display 0
Press a button to see transitions
State.java
// The 4 states of the calculator state machine
public enum State {
    Input1,    // entering first number
    OpReady,   // operator selected, waiting for second number
    Input2,    // entering second number
    HasResult  // result shown, ready for next calc
}
Lab 6: Discrete Event Simulation (Car Wash)

A full simulation engine from scratch

A car wash with fast and slow machines. Cars arrive randomly (exponential distribution), wait in a bounded queue, and depart after being washed (uniform distribution). Built on a reusable simulation framework: Simulator drives an EventQueue (priority queue), each Event modifies the State and may schedule new events. The random package was provided by the course.

random ExponentialRandomStream UniformRandomStream Provided by course
→ used by →
simulation Simulator Event EventQueue State
↑ extends
carwash CarWashState ArrivalEvent DepartureEvent CloseEvent · StopEvent EventFactory · Car
Lab 6 · Car Wash Simulation
Discrete event simulation ★ Live demo

Run the exact simulation from Main.java, 2 fast machines, 2 slow machines, queue of 5, λ=2, seed=1234. Step through each event or run the full simulation and see the event log, machine states, and queue live. Adjust the parameters and re-run for different results.

Discrete event sim Priority queue Exponential distribution Uniform distribution Observer pattern 3 packages
Live Demo: Interactive Simulation
Fast Machines
Slow Machines
Waiting Queue
Time0.00
Arrived0
Served0
Rejected0
Event Log
TimeEventCarFFFSQRej

UML class diagram showing the architecture: inheritance, composition, and dependencies between the three packages.

UML Class Diagram

What I learned

What an ArrayList does for you.

It is an ordinary array that gets copied to a bigger one when it fills up. Writing it made it clear why adding at the end is cheap on average and removing from the middle is not.

Let the model not know about the screen.

In the room game the level only says that something changed. The window listens and redraws itself, so the rules never mention graphics.

Time can jump.

The car wash simulation does not count seconds. It takes the next event from a queue sorted by time and moves the clock straight to it.

A queue in a circle.

The FIFO queue wraps around with modulo, so nothing has to be shifted when the first element leaves.