SyntaxPilot
Courses/Low-Level Design/Lesson 61
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 61 of 90

Design an elevator system 1: model and states

elevator requirementsElevatorElevatorCarFloorButtoninternal vs external requestsDirectionelevator state machinedoor stateDisplayrequest queue

These are the notes for Low-Level Design (LLD) episode 61, the first half of the elevator (lift) machine-coding problem. After the parking lot (episodes 59 and 60), the elevator is the problem interviewers ask most. Part 1 builds the model: the requirements, the entities (Elevator vs ElevatorCar, Floor, Button, Display, Request), the Direction and door state, an elevator state machine that refuses dangerous moves, internal vs external requests, and the request queue. Part 2 (episode 62) adds scheduling and many elevators.

How the code was run: every program was saved as Main.java in a fresh folder and run with javac Main.java && java -cp . Main on OpenJDK 21. Every output below is the real output, pasted exactly, including exceptions. The office building and its ten floors are made up for teaching.

1. The problem: 9:55 a.m. at a ten-floor office

Five minutes to ten. An office with floors 0 (ground) to 9 and one lift. Everyone is late. Imagine our software runs that lift, and it has four bugs:

What people see What went wrong in the code Fixed by
The door opens between floors The car "thinks" it stopped; nothing forbids moving with the door open Enums and a state machine
Asha on floor 4 presses DOWN, gets in, rides up to 9 A request stored only the floor, not the direction External request = floor + direction
Someone presses 12 in a 0-9 building Nobody checked the floor Validation in submit
The lift goes up, down, up, down Requests served in the order pressed Measured today; scheduling in part 2

2. Requirements

A requirement is something the system must do, agreed with the interviewer before you write code (episode 55: clarify first). Ask, and write them down:

Functional requirements (what it does):

  1. From a floor, a person calls the lift and says UP or DOWN (hall buttons).
  2. Inside the car, a person chooses a destination floor (car buttons).
  3. The car moves floor by floor, stops, opens and closes its door.
  4. A display shows the current floor and direction.

Non-functional requirement (a quality the system must have): safety. The car must never move with its door open, and never open its door while moving.

Out of scope today: several cars, smarter ordering of requests (scheduling), weight limits, emergencies. Saying what is out of scope is part of a good answer; part 2 adds the first two.

Clarifying questions and our assumptions:

Question Our assumption
How many floors? 10 (floors 0 to 9)
How many cars? One today; several in part 2
Does a hall call say the direction? Yes: each floor has an UP and a DOWN button
What happens to an invalid floor? Refuse it at once with an exception
How do we simulate time? In ticks: one floor, or one door action, per tick

3. Entities: the nouns become classes

An entity is a thing in the problem that has its own data and its own rules. The trick from episode 20 (object-oriented analysis): underline the nouns in the requirements.

Entity What it is What it knows
Building The whole building how many floors; where requests go
Floor One floor its number; its UP and DOWN hall buttons
Elevator The whole system: car + shaft + controller (a word, not always a class in part 1)
ElevatorCar The cabin that moves and carries people floor, direction, state, door, display, requests
Button A button: on a floor (hall button) or inside the car (car button) which request it makes
Display The lamp above the door: [4^] = floor 4, going up how to show floor + direction
Request One call for the lift a floor (and for hall calls, a direction)

Elevator vs ElevatorCar. People use "elevator" for two things: the whole system and the moving box. Keep them apart in your design: ElevatorCar is the cabin. In part 2 one building gets several cars, and a controller (the "elevator system") chooses among them. If you call the cabin Elevator now, part 2 gets confusing.

4. The obvious model: three booleans (and how it breaks)

A boolean holds just true or false. The first idea is three flags: moving, doorOpen, goingUp. Every method sets the flags it cares about.

class Elevator {                                        // the obvious way: three booleans
    int floor = 0;
    boolean moving = false, doorOpen = false, goingUp = true;
    void openDoor()  { doorOpen = true;  System.out.println("door opens at floor " + floor); }
    void closeDoor() { doorOpen = false; }
    void moveUp()    { moving = true; goingUp = true; floor++; System.out.println("moving up to " + floor); }
    void stop()      { moving = false; }
}
public class Main {
    public static void main(String[] args) {
        Elevator lift = new Elevator();
        lift.openDoor();                                    // passengers get in
        lift.moveUp();                                      // someone pressed 2... nobody closed the door
        lift.moveUp();
        lift.openDoor();                                    // and it opens again, still moving
        System.out.println("moving=" + lift.moving + " doorOpen=" + lift.doorOpen + " goingUp=" + lift.goingUp);
        if (lift.moving && lift.doorOpen) System.out.println("DANGER: moving with the door open!");
        lift.stop();
        System.out.println("stopped, goingUp=" + lift.goingUp + "   <- going up while standing still?");
    }
}

Output:

door opens at floor 0
moving up to 1
moving up to 2
door opens at floor 2
moving=true doorOpen=true goingUp=true
DANGER: moving with the door open!
stopped, goingUp=true   <- going up while standing still?

The compiler was happy. The building would not be.

Why it failed

  • Three booleans give 2 × 2 × 2 = 8 combinations. Only a few make sense. "Moving with the door open" is one of the nonsense ones, and nothing stopped it.
  • Every method must remember the rules. openDoor doesn't know it should check moving; moveUp doesn't check doorOpen.
  • Flags drift apart. After stop(), goingUp is still true: the lift claims to be going up while standing still.
moving doorOpen goingUp Makes sense?
false false false yes: idle, or stopped
false false true only if it is about to go up
false true false yes: stopped, door open
false true true yes: stopped going up, door open
true false false yes: moving down
true false true yes: moving up
true true false no: moving with the door open
true true true no: moving with the door open

5. Direction, door state and the elevator state machine

A state is what an object is doing right now. Instead of loose flags, we name the states with enums (episode 3: a type with a fixed list of values; you can't make up a new value by accident):

enum Direction { UP, DOWN, IDLE }               // IDLE = not going anywhere
enum ElevatorState { IDLE, MOVING, STOPPED }    // what the car is doing
enum DoorState { OPEN, CLOSED }                 // the door is a separate thing
  • Direction: which way the car is heading. IDLE means "no direction": nothing to do.
  • ElevatorState: IDLE = no work; MOVING = between floors; STOPPED = standing at a floor (maybe for people to get in).
  • DoorState: OPEN or CLOSED.

One variable of each type: the car is always in exactly one value of each. No "half up".

A state machine (episode 37, the State pattern) is the list of states plus the allowed moves between them. A move from one state to another is a transition. Ours:

From \ To IDLE MOVING STOPPED
IDLE — ✅ start a trip ❌
MOVING ❌ ✅ next floor ✅ arrive
STOPPED ✅ no more work ✅ next trip ❌

And two safety rules that involve the door:

  • move() is allowed only when the door is CLOSED.
  • openDoor() is allowed only when the car is not MOVING.

A wrong move throws an IllegalStateException: Java's built-in unchecked exception for "you can't do that right now, in this state".

enum Direction { UP, DOWN, IDLE }   enum ElevatorState { IDLE, MOVING, STOPPED }   enum DoorState { OPEN, CLOSED }
class ElevatorCar {
    private int floor = 0;  private Direction direction = Direction.IDLE;
    private ElevatorState state = ElevatorState.IDLE;  private DoorState door = DoorState.CLOSED;
    private void go(ElevatorState to) {                     // the state machine: only allowed moves
        boolean ok = switch (state) {
            case IDLE    -> to == ElevatorState.MOVING;
            case MOVING  -> to == ElevatorState.MOVING || to == ElevatorState.STOPPED;
            case STOPPED -> to == ElevatorState.MOVING || to == ElevatorState.IDLE;
        };
        if (!ok) throw new IllegalStateException(state + " -> " + to + " is not allowed");  state = to;
    }
    void move(Direction d) {
        if (door == DoorState.OPEN) throw new IllegalStateException("can't move: door is OPEN");
        go(ElevatorState.MOVING);  direction = d;  floor += d == Direction.UP ? 1 : -1; }
    void openDoor() {
        if (state == ElevatorState.MOVING) throw new IllegalStateException("can't open: car is MOVING");
        door = DoorState.OPEN; }
    void stop() { go(ElevatorState.STOPPED); }      void closeDoor() { door = DoorState.CLOSED; }
    public String toString() { return "floor " + floor + ", " + state + ", door " + door + ", " + direction; }
}
public class Main { public static void main(String[] args) {
    ElevatorCar car = new ElevatorCar();
    car.move(Direction.UP); car.move(Direction.UP); car.stop(); car.openDoor(); System.out.println(car);
    try { car.move(Direction.UP); } catch (Exception e) { System.out.println("refused: " + e.getMessage()); }
    car.closeDoor();  car.move(Direction.UP);  System.out.println(car);
    car.openDoor();                                         // open the door while moving?
}}

Output:

floor 2, STOPPED, door OPEN, UP
refused: can't move: door is OPEN
floor 3, MOVING, door CLOSED, UP
Exception in thread "main" java.lang.IllegalStateException: can't open: car is MOVING
    at ElevatorCar.openDoor(Main.java:17)
    at Main.main(Main.java:27)

Line by line: floor 2, stopped, door open. Trying to move with the door open: refused. Close, move: floor 3, moving. Opening the door while moving: IllegalStateException: can't open: car is MOVING, the program stops. The impossible state from section 4 can no longer happen.

Why private fields? So that only the car's own methods can change the state, and every change goes through the checks (encapsulation, episode 6). If state were public, any code could write car.state = MOVING and skip the rules.

Why a switch for transitions? It keeps all the rules in one place you can read like the table above. The switch expression (switch (state) { case IDLE -> ...; }) must cover every enum value, so if you add a new state, the compiler reminds you to write its rules. (Try deleting the case STOPPED line: error: the switch expression does not cover all possible input values.)

6. The real-life idea: the lift panel

A real lift already shows this design:

In a real lift In the design
The lamp above the door: "4" and an up arrow Display: floor + Direction
UP and DOWN buttons in the lobby: "I'm here, I want to go up" ExternalRequest(floor, direction)
The number panel inside: "take me to 7" InternalRequest(floor)
The door sensor that won't let the motor start until the door is shut The state machine rule: move only if CLOSED

7. Internal vs external requests

The obvious way: a request is just an int floor. But then Asha's DOWN is lost, and the car can't tell whether to pick her up on its way up. There are really two kinds of request:

External request (hall call) Internal request (car call)
Made by A hall button on a floor A car button inside the cabin
Says "I'm on floor 4, I want to go DOWN" "Take me to floor 7"
Data floor + direction destination floor
Class record ExternalRequest(int floor, Direction direction) record InternalRequest(int floor)

Both are requests, so they share an interface Request. Two Java features make this neat:

  • A record (episode 3) is a short class that just holds values. Java writes the constructor, the getters (floor()), equals, hashCode and a readable toString (ExternalRequest[floor=4, direction=DOWN]) for you.
  • A sealed interface (episode 8) lists exactly which classes may implement it: sealed interface Request permits ExternalRequest, InternalRequest. Nobody can add a third kind of request by accident, and a switch over a Request can be checked for completeness.

A Button doesn't move anything. It only knows which request it makes, and hands it over when pressed. A Floor has an up and a down button. The Building validates every request: a floor must exist (0 <= floor < floors), else IllegalArgumentException (Java's unchecked exception for "this argument is invalid").

import java.util.*;   enum Direction { UP, DOWN, IDLE }
sealed interface Request permits ExternalRequest, InternalRequest { int floor(); }
record ExternalRequest(int floor, Direction direction) implements Request {}  // hall button: "on 4, going DOWN"
record InternalRequest(int floor) implements Request {}                       // car button: "take me to 7"
class Building {
    final int floors;  final Queue<Request> requests = new ArrayDeque<>();     // the request queue
    Building(int floors) { this.floors = floors; }
    void submit(Request r) {
        if (r.floor() < 0 || r.floor() >= floors)
            throw new IllegalArgumentException("no floor " + r.floor() + " in a " + floors + "-floor building");
        requests.add(r);  System.out.println("queued " + r); } }
class Button {                                            // a button only knows which request it makes
    private final Building building;  private final Request request;
    Button(Building b, Request r) { building = b; request = r; }
    void press() { building.submit(request); }
}
class Floor {                                             // each floor has an UP and a DOWN hall button
    final Button up, down;
    Floor(Building b, int n) { up = new Button(b, new ExternalRequest(n, Direction.UP));
                               down = new Button(b, new ExternalRequest(n, Direction.DOWN)); }
}
public class Main { public static void main(String[] args) {
    Building office = new Building(10);                   // floors 0 to 9
    new Floor(office, 0).up.press();  new Floor(office, 4).down.press();
    new Button(office, new InternalRequest(7)).press();   // a button inside the car
    System.out.println(office.requests.size() + " waiting, first: " + office.requests.peek());
    new Button(office, new InternalRequest(12)).press();
}}

Output:

queued ExternalRequest[floor=0, direction=UP]
queued ExternalRequest[floor=4, direction=DOWN]
queued InternalRequest[floor=7]
3 waiting, first: ExternalRequest[floor=0, direction=UP]
Exception in thread "main" java.lang.IllegalArgumentException: no floor 12 in a 10-floor building
    at Building.submit(Main.java:10)
    at Button.press(Main.java:15)
    at Main.main(Main.java:27)

Notice the record toString doing the printing for us, and the floor-12 press refused with a clear message instead of a lift trying to reach a floor that isn't there.

Why does the button keep a request, instead of the floor number? Because then a hall button and a car button are the same class (Button) with different requests inside. Pressing works the same everywhere: press() → building.submit(request). Later, a "door open" button or an alarm button is just a different action.

8. The request queue

Requests wait in a request queue. A queue is like the line at a ticket counter: you join at the back and the front is served first. That rule is FIFO, "first in, first out" (also "first come, first served").

Java's fast general-purpose queue is ArrayDeque (a "double-ended queue" backed by an array; episode 4). The three methods we use:

Method Does If empty
add(x) put x at the back —
peek() look at the front, don't remove it returns null
poll() remove the front and return it returns null

Test: the car is at floor 0. People press 5, 1, 6 and 2, in that order. Served in that order, how far does the car travel?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Queue<Integer> requests = new ArrayDeque<>(List.of(5, 1, 6, 2));   // pressed in this order
        int floor = 0, moved = 0;
        System.out.println("car at " + floor + ", requests " + requests);
        while (!requests.isEmpty()) {
            int next = requests.poll();                                   // first come, first served
            moved += Math.abs(next - floor);
            System.out.println("go " + floor + " -> " + next + "   (moved " + moved + " floors so far)");
            floor = next;
        }
        System.out.println("total: " + moved + " floors. One trip up, 0 -> 6, serves them all in 6.");
    }
}

Output:

car at 0, requests [5, 1, 6, 2]
go 0 -> 5   (moved 5 floors so far)
go 5 -> 1   (moved 9 floors so far)
go 1 -> 6   (moved 14 floors so far)
go 6 -> 2   (moved 18 floors so far)
total: 18 floors. One trip up, 0 -> 6, serves them all in 6.

18 floors where one trip up, serving 1, 2, 5 and 6 on the way, needs 6: three times the travel and the waiting. The model is right; the order is wrong. Choosing a better order is called scheduling: part 2 (episode 62) compares FCFS, shortest seek time first, SCAN and LOOK.

9. One tick at a time: the running demo

How does the car actually run? We split time into ticks. A tick is one small step of simulated time: the car moves one floor, or the door does one thing. Every tick, step() looks at the front request and does exactly one thing:

  1. Door open? Close it.
  2. No request? Go IDLE, direction IDLE.
  3. At the request's floor? STOPPED, door OPEN, remove the request.
  4. Otherwise: set the direction towards the request and move one floor (MOVING).

Because nothing depends on a real clock, the same ticks always give the same output: easy to test (episode 53).

This version folds everything together. Direction carries its arrow (an enum with a field, episode 3), and Display turns floor + direction into [4^].

enum Direction { UP("^"), DOWN("v"), IDLE("-");  final String arrow;  Direction(String a) { arrow = a; } }
enum ElevatorState { IDLE, MOVING, STOPPED }   enum DoorState { OPEN, CLOSED }
sealed interface Request permits ExternalRequest, InternalRequest { int floor(); }
record ExternalRequest(int floor, Direction direction) implements Request {}
record InternalRequest(int floor) implements Request {}
class Display { String show(int f, Direction d) { return "[" + f + d.arrow + "]"; } }   // above the door
class ElevatorCar {
    int floor = 0;  Direction dir = Direction.IDLE;  ElevatorState state = ElevatorState.IDLE;
    DoorState door = DoorState.CLOSED;  final Display display = new Display();
    final java.util.Queue<Request> requests = new java.util.ArrayDeque<>();
    void step() {                                         // one tick of time
        if (door == DoorState.OPEN) { door = DoorState.CLOSED; log("door closes"); return; }
        Request r = requests.peek();
        if (r == null) { state = ElevatorState.IDLE; dir = Direction.IDLE; log("nothing to do"); return; }
        if (r.floor() == floor) {                         // arrived: stop and open
            requests.poll();  state = ElevatorState.STOPPED;  door = DoorState.OPEN;
            log("door opens for " + r);  return; }
        dir = r.floor() > floor ? Direction.UP : Direction.DOWN;
        state = ElevatorState.MOVING;  floor += dir == Direction.UP ? 1 : -1;  log("moving");
    }
    private void log(String what) {
        System.out.println(display.show(floor, dir) + " " + state + ", door " + door + ": " + what); }
}
public class Main { public static void main(String[] args) {   ElevatorCar car = new ElevatorCar();
    car.requests.add(new ExternalRequest(2, Direction.UP));   for (int t = 0; t < 3; t++) car.step();
    car.requests.add(new InternalRequest(4));                   // they get in and press 4
    for (int t = 0; t < 6; t++) car.step();
}}

Output:

[1^] MOVING, door CLOSED: moving
[2^] MOVING, door CLOSED: moving
[2^] STOPPED, door OPEN: door opens for ExternalRequest[floor=2, direction=UP]
[2^] STOPPED, door CLOSED: door closes
[3^] MOVING, door CLOSED: moving
[4^] MOVING, door CLOSED: moving
[4^] STOPPED, door OPEN: door opens for InternalRequest[floor=4]
[4^] STOPPED, door CLOSED: door closes
[4-] IDLE, door CLOSED: nothing to do

Reading the display column: [2^] = floor 2, going up; [4-] = floor 4, no direction (idle). Note that step() only ever makes legal moves: it opens the door only after setting STOPPED, and moves only after the door has been closed in an earlier tick. The mini project below adds the go() checks back in, so even a bug in step() would be refused.

10. The class diagram

Building (floors 0 to 9)
 ├─has──▶ Floor ×10 ── Button UP · Button DOWN   (hall buttons → ExternalRequest)
 └─has──▶ ElevatorCar
            ├─ ElevatorState: IDLE ─▶ MOVING ─▶ STOPPED ─▶ IDLE
            ├─ DoorState: OPEN / CLOSED   (never OPEN while MOVING)
            ├─ Direction: UP / DOWN / IDLE
            ├─ Display  "[4^]"
            ├─ Button ×10 inside           (car buttons → InternalRequest)
            └─ Queue<Request>   first come, first served (for now)

In UML terms (episode 18): Building composes its Floors (a floor doesn't exist without the building); ElevatorCar composes its Display and its car buttons; ExternalRequest and InternalRequest realize Request.

11. Common mistakes

Mistake What you see Why Fix
Booleans for moving, doorOpen, goingUp DANGER: moving with the door open! 8 combinations, no rule Enums + a state machine
No check before moving (with the check) IllegalStateException: can't move: door is OPEN Every method must guard the rule Check the door in move()
Opening the door while moving Exception in thread "main" java.lang.IllegalStateException: can't open: car is MOVING (that's the fix working) Only open when not MOVING
A request is just an int floor rider wanting DOWN is taken UP The direction is lost ExternalRequest(floor, direction)
No floor validation (with it) IllegalArgumentException: no floor 12 in a 10-floor building (that's the fix working) Check 0 <= floor < floors
Public mutable state any code writes car.state = MOVING Rules can be skipped private fields, changes only through methods
Serving requests in pressed order total: 18 floors. One trip up, 0 -> 6, serves them all in 6. FIFO zigzags Scheduling (part 2)
A switch expression missing a state error: the switch expression does not cover all possible input values A new enum value has no rule Add the case (the compiler protects you)
Calling the cabin Elevator part 2's "elevator system" vs "elevator" confusion One word, two meanings ElevatorCar for the cabin

Mini project: a safe, validated elevator car

Put it all together: requests are validated, duplicates are ignored (a LinkedHashSet keeps the pressed order but refuses repeats), and every state change goes through go(), so even a bug in step() can't make an illegal move.

import java.util.*;

enum Direction {
    UP("^"), DOWN("v"), IDLE("-");
    final String arrow;
    Direction(String arrow) { this.arrow = arrow; }
}
enum ElevatorState { IDLE, MOVING, STOPPED }
enum DoorState { OPEN, CLOSED }

sealed interface Request permits ExternalRequest, InternalRequest { int floor(); }
record ExternalRequest(int floor, Direction direction) implements Request {}
record InternalRequest(int floor) implements Request {}

class Display {
    String show(int floor, Direction d) { return "[" + floor + d.arrow + "]"; }
}

class ElevatorCar {
    private final int floors;
    private int floor = 0;
    private Direction direction = Direction.IDLE;
    private ElevatorState state = ElevatorState.IDLE;
    private DoorState door = DoorState.CLOSED;
    private final Set<Integer> stops = new LinkedHashSet<>();      // pressed order, no duplicates
    private final Display display = new Display();

    ElevatorCar(int floors) { this.floors = floors; }

    void submit(Request r) {
        if (r.floor() < 0 || r.floor() >= floors)
            throw new IllegalArgumentException("no floor " + r.floor() + " in a " + floors + "-floor building");
        if (!stops.add(r.floor())) System.out.println("   (floor " + r.floor() + " already requested)");
    }

    private void go(ElevatorState to) {                            // the state machine
        boolean ok = switch (state) {
            case IDLE    -> to == ElevatorState.MOVING || to == ElevatorState.STOPPED;
            case MOVING  -> to == ElevatorState.MOVING || to == ElevatorState.STOPPED;
            case STOPPED -> to == ElevatorState.MOVING || to == ElevatorState.IDLE || to == ElevatorState.STOPPED;
        };
        if (!ok) throw new IllegalStateException(state + " -> " + to + " is not allowed");
        state = to;
    }

    boolean busy() { return !stops.isEmpty() || door == DoorState.OPEN; }

    void step() {
        if (door == DoorState.OPEN) { door = DoorState.CLOSED; log("door closes"); return; }
        if (stops.isEmpty()) {
            if (state != ElevatorState.IDLE) go(ElevatorState.IDLE);
            direction = Direction.IDLE; log("idle"); return;
        }
        int target = stops.iterator().next();
        if (target == floor) {
            stops.remove(target);
            go(ElevatorState.STOPPED);
            door = DoorState.OPEN;                                  // allowed: we are not MOVING
            log("door opens"); return;
        }
        if (door == DoorState.OPEN) throw new IllegalStateException("can't move: door is OPEN");
        direction = target > floor ? Direction.UP : Direction.DOWN;
        go(ElevatorState.MOVING);
        floor += direction == Direction.UP ? 1 : -1;
        log("moving");
    }

    private void log(String what) {
        System.out.println(display.show(floor, direction) + " " + state + ", door " + door + ": " + what);
    }
}

public class Main {
    public static void main(String[] args) {
        ElevatorCar car = new ElevatorCar(10);
        car.submit(new ExternalRequest(3, Direction.UP));           // hall call on floor 3
        car.submit(new ExternalRequest(3, Direction.UP));           // pressed again
        while (car.busy()) car.step();
        car.submit(new InternalRequest(1));                         // inside: take me to 1
        while (car.busy()) car.step();
        car.step();
        try { car.submit(new InternalRequest(10)); }
        catch (IllegalArgumentException e) { System.out.println("refused: " + e.getMessage()); }
    }
}

Output:

   (floor 3 already requested)
[1^] MOVING, door CLOSED: moving
[2^] MOVING, door CLOSED: moving
[3^] MOVING, door CLOSED: moving
[3^] STOPPED, door OPEN: door opens
[3^] STOPPED, door CLOSED: door closes
[2v] MOVING, door CLOSED: moving
[1v] MOVING, door CLOSED: moving
[1v] STOPPED, door OPEN: door opens
[1v] STOPPED, door CLOSED: door closes
[1-] IDLE, door CLOSED: idle
refused: no floor 10 in a 10-floor building

Try it yourself: change step() so it forgets to close the door before moving (delete the first line). The go() and door checks turn that bug into an exception instead of an accident.

Practice

1. Add a MAINTENANCE state. A technician can put an idle or stopped car into maintenance; nothing moves in maintenance; only endMaintenance() brings it back to IDLE. A moving car can't enter maintenance.

Answer
enum Direction { UP, DOWN, IDLE }
enum ElevatorState { IDLE, MOVING, STOPPED, MAINTENANCE }
enum DoorState { OPEN, CLOSED }
class ElevatorCar {
    private int floor = 0;
    private ElevatorState state = ElevatorState.IDLE;
    private DoorState door = DoorState.CLOSED;
    private void go(ElevatorState to) {
        boolean ok = switch (state) {
            case IDLE        -> to == ElevatorState.MOVING || to == ElevatorState.MAINTENANCE;
            case MOVING      -> to == ElevatorState.MOVING || to == ElevatorState.STOPPED;
            case STOPPED     -> to == ElevatorState.MOVING || to == ElevatorState.IDLE || to == ElevatorState.MAINTENANCE;
            case MAINTENANCE -> to == ElevatorState.IDLE;          // only a technician brings it back
        };
        if (!ok) throw new IllegalStateException(state + " -> " + to + " is not allowed");
        state = to;
    }
    void move(Direction d) {
        if (door == DoorState.OPEN) throw new IllegalStateException("can't move: door is OPEN");
        go(ElevatorState.MOVING);  floor += d == Direction.UP ? 1 : -1;
    }
    void stop() { go(ElevatorState.STOPPED); }
    void startMaintenance() { go(ElevatorState.MAINTENANCE); }
    void endMaintenance() { go(ElevatorState.IDLE); }
    public String toString() { return "floor " + floor + ", " + state + ", door " + door; }
}
public class Main {
    public static void main(String[] args) {
        ElevatorCar car = new ElevatorCar();
        car.startMaintenance();  System.out.println(car);
        try { car.move(Direction.UP); } catch (IllegalStateException e) { System.out.println("refused: " + e.getMessage()); }
        car.endMaintenance();  car.move(Direction.UP);  System.out.println(car);
        car.startMaintenance();                                   // while MOVING: not allowed
    }
}

Output:

floor 0, MAINTENANCE, door CLOSED
refused: MAINTENANCE -> MOVING is not allowed
floor 1, MOVING, door CLOSED
Exception in thread "main" java.lang.IllegalStateException: MOVING -> MAINTENANCE is not allowed
    at ElevatorCar.go(Main.java:15)
    at ElevatorCar.startMaintenance(Main.java:23)
    at Main.main(Main.java:33)

2. People press the same floor many times. Keep the pressed order, but ignore a floor that's already waiting.

Answer

A LinkedHashSet remembers insertion order (like a list) and refuses duplicates (like a set). add returns false for a repeat.

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Set<Integer> requests = new LinkedHashSet<>();             // keeps the pressed order, ignores repeats
        for (int floor : new int[] { 5, 5, 1, 5, 6, 1, 2 }) {
            boolean added = requests.add(floor);
            System.out.println("press " + floor + (added ? " -> queued " : " -> already queued ") + requests);
        }
        Iterator<Integer> it = requests.iterator();
        int first = it.next();  it.remove();                        // take from the front
        System.out.println("serve " + first + ", left " + requests);
    }
}

Output:

press 5 -> queued [5]
press 5 -> already queued [5]
press 1 -> queued [5, 1]
press 5 -> already queued [5, 1]
press 6 -> queued [5, 1, 6]
press 1 -> already queued [5, 1, 6]
press 2 -> queued [5, 1, 6, 2]
serve 5, left [1, 6, 2]

3. Add a weight limit. People enter and leave; closeDoor() refuses while the load is over the limit (use a made-up 544 kg).

Answer
enum DoorState { OPEN, CLOSED }
class ElevatorCar {
    static final int MAX_KG = 544;                                  // a made-up limit: 8 people x 68 kg
    private int loadKg = 0;  private DoorState door = DoorState.OPEN;
    void enter(int kg) { loadKg += kg; System.out.println("in: " + kg + " kg, load " + loadKg + " kg"); }
    void leave(int kg) { loadKg -= kg; System.out.println("out: " + kg + " kg, load " + loadKg + " kg"); }
    void closeDoor() {
        if (loadKg > MAX_KG) { System.out.println("OVERLOAD: " + loadKg + " > " + MAX_KG + " kg, door stays OPEN"); return; }
        door = DoorState.CLOSED;  System.out.println("door CLOSED");
    }
}
public class Main {
    public static void main(String[] args) {
        ElevatorCar car = new ElevatorCar();
        for (int kg : new int[] { 70, 82, 65, 90, 75, 68, 80, 70 }) car.enter(kg);
        car.closeDoor();
        car.leave(80);
        car.closeDoor();
    }
}

Output:

in: 70 kg, load 70 kg
in: 82 kg, load 152 kg
in: 65 kg, load 217 kg
in: 90 kg, load 307 kg
in: 75 kg, load 382 kg
in: 68 kg, load 450 kg
in: 80 kg, load 530 kg
in: 70 kg, load 600 kg
OVERLOAD: 600 > 544 kg, door stays OPEN
out: 80 kg, load 520 kg
door CLOSED

Design note: overload is a rule about closing the door, so it lives in closeDoor(). The car can't move until the door is closed, so it can't move overloaded either.

4. Using the running-demo car from section 9, how many ticks does it take to serve car calls 5, 1, 6, 2 from floor 0? Predict first, then run.

Answer

Prediction: 18 floors moved (section 8) + 4 stops × 2 ticks (open, close) = 26 ticks.

enum Direction { UP("^"), DOWN("v"), IDLE("-");  final String arrow;  Direction(String a) { arrow = a; } }
enum ElevatorState { IDLE, MOVING, STOPPED }   enum DoorState { OPEN, CLOSED }
sealed interface Request permits ExternalRequest, InternalRequest { int floor(); }
record ExternalRequest(int floor, Direction direction) implements Request {}
record InternalRequest(int floor) implements Request {}
class Display { String show(int f, Direction d) { return "[" + f + d.arrow + "]"; } }   // above the door
class ElevatorCar {
    int floor = 0;  Direction dir = Direction.IDLE;  ElevatorState state = ElevatorState.IDLE;
    DoorState door = DoorState.CLOSED;  final Display display = new Display();
    final java.util.Queue<Request> requests = new java.util.ArrayDeque<>();
    void step() {                                         // one tick of time
        if (door == DoorState.OPEN) { door = DoorState.CLOSED; log("door closes"); return; }
        Request r = requests.peek();
        if (r == null) { state = ElevatorState.IDLE; dir = Direction.IDLE; log("nothing to do"); return; }
        if (r.floor() == floor) {                         // arrived: stop and open
            requests.poll();  state = ElevatorState.STOPPED;  door = DoorState.OPEN;
            log("door opens for " + r);  return; }
        dir = r.floor() > floor ? Direction.UP : Direction.DOWN;
        state = ElevatorState.MOVING;  floor += dir == Direction.UP ? 1 : -1;  log("moving");
    }
    private void log(String what) {
        System.out.println(display.show(floor, dir) + " " + state + ", door " + door + ": " + what); }
}
public class Main { public static void main(String[] args) {   ElevatorCar car = new ElevatorCar();
    for (int f : new int[] { 5, 1, 6, 2 }) car.requests.add(new InternalRequest(f));
    int ticks = 0;
    while (!car.requests.isEmpty() || car.door == DoorState.OPEN) { car.step(); ticks++; }
    System.out.println("ticks: " + ticks);
}}

Output:

[1^] MOVING, door CLOSED: moving
[2^] MOVING, door CLOSED: moving
[3^] MOVING, door CLOSED: moving
[4^] MOVING, door CLOSED: moving
[5^] MOVING, door CLOSED: moving
[5^] STOPPED, door OPEN: door opens for InternalRequest[floor=5]
[5^] STOPPED, door CLOSED: door closes
[4v] MOVING, door CLOSED: moving
[3v] MOVING, door CLOSED: moving
[2v] MOVING, door CLOSED: moving
[1v] MOVING, door CLOSED: moving
[1v] STOPPED, door OPEN: door opens for InternalRequest[floor=1]
[1v] STOPPED, door CLOSED: door closes
[2^] MOVING, door CLOSED: moving
[3^] MOVING, door CLOSED: moving
[4^] MOVING, door CLOSED: moving
[5^] MOVING, door CLOSED: moving
[6^] MOVING, door CLOSED: moving
[6^] STOPPED, door OPEN: door opens for InternalRequest[floor=6]
[6^] STOPPED, door CLOSED: door closes
[5v] MOVING, door CLOSED: moving
[4v] MOVING, door CLOSED: moving
[3v] MOVING, door CLOSED: moving
[2v] MOVING, door CLOSED: moving
[2v] STOPPED, door OPEN: door opens for InternalRequest[floor=2]
[2v] STOPPED, door CLOSED: door closes
ticks: 26

5. (Thinking) Why is Direction.IDLE needed? Couldn't a stopped car just keep its last direction?

Answer

The direction matters for picking people up: a car going UP should stop for an UP hall call, not a DOWN one. A car with nothing to do has no direction, so it can answer any call. If it kept "UP" after its last stop, part 2's dispatcher would think it's still heading up and might skip it for a DOWN call. IDLE says honestly: free.

Quick quiz

The car is STOPPED at floor 3 with the door OPEN. Which call throws IllegalStateException? (a) openDoor() (b) closeDoor() (c) move(Direction.UP) (d) toString()

Answer

(c) move(Direction.UP). move() checks the door first: it's OPEN, so it throws can't move: door is OPEN (the program in section 5 prints exactly this as refused: can't move: door is OPEN). openDoor() is allowed because the car is not MOVING; closeDoor() and toString() never throw.

Interview questions

  1. What are the main classes of an elevator system? Building, Floor, ElevatorCar, Button (hall and car), Request (external and internal), Display, the enums Direction, ElevatorState, DoorState, and in part 2 an ElevatorController.
  2. Why not booleans for the car's state? n booleans give 2ⁿ combinations, most invalid ("moving with the door open"). Enums give exactly the valid values, and a state machine lists the valid transitions.
  3. What's the difference between an internal and an external request? External: from a hall button, with floor and direction. Internal: from inside the car, with only the destination. The direction lets a car decide whether to stop for a hall call on its way.
  4. Where does the "never move with the door open" rule live? Inside ElevatorCar, in move() (door must be CLOSED) and openDoor() (car must not be MOVING), with the fields private so nobody can bypass them.
  5. How do you model the state machine? An enum of states and a transition table (a switch expression or an EnumMap<State, Set<State>>); every change goes through one go(to) method that throws IllegalStateException on an invalid transition. For per-state behaviour that grows, use the State pattern (episode 37).
  6. Elevator vs ElevatorCar? "Elevator" can mean the whole system; ElevatorCar is the cabin. Separate names keep the multi-car design (part 2) clear.
  7. How do you test an elevator without real time? Simulate in ticks: step() does one thing per tick, so a test can call it n times and check the output; no Thread.sleep, no real clock.
  8. What's wrong with a FIFO request queue? It serves calls in pressed order, so the car zigzags: 5, 1, 6, 2 from floor 0 costs 18 floors instead of 6. Use a scheduling strategy (SCAN/LOOK, part 2).
  9. How would you handle the same button pressed many times? Keep stops in a Set (a LinkedHashSet to keep order); light the button once.
  10. How would you add an emergency or maintenance mode? A new ElevatorState value with its own transitions (the switch expression forces you to write them), and checks in move().

Glossary

Term Meaning, with an example
Elevator system (LLD problem) A classic machine-coding problem: model a building's lifts, their requests and states, then schedule them
Machine-coding round An interview round where you design and code a small working system, usually in 60-120 minutes
Requirement Something the system must do, agreed before coding: "a person on a floor can call the lift with UP or DOWN"
Functional requirement What the system does: call, choose a floor, move, open the door
Non-functional requirement A quality it must have: safety ("never move with the door open"), speed, fairness
Out of scope What you agree not to build now: several cars, scheduling (part 2)
Entity A thing in the problem with its own data and rules: ElevatorCar, Floor, Button
Elevator Usually the whole system: car + shaft + controller
ElevatorCar The cabin that moves and carries people; one class per cabin
Building Holds the floors and receives requests; validates floor numbers
Floor One level of the building, with an UP and a DOWN hall button
Button A thing you press that makes a request; it knows only which request
Hall button A button on a floor, outside the lift: UP or DOWN
Car button A button inside the cabin: a floor number
Display The lamp above the door showing floor and direction: [4^]
Request One call for the lift: a floor, and for hall calls a direction
External request A hall call: ExternalRequest(4, DOWN) = "I'm on 4, going down"
Internal request A car call: InternalRequest(7) = "take me to 7"
Direction Which way the car is heading: UP, DOWN, or IDLE (none)
State What an object is doing right now: the car is MOVING
ElevatorState The car's states: IDLE (no work), MOVING (between floors), STOPPED (at a floor)
Door state The door's own state, separate from the car's: OPEN or CLOSED
State machine The states plus the allowed moves between them; anything else is refused
Transition One move from a state to another: MOVING → STOPPED
Invalid transition A move the machine doesn't allow: IDLE → STOPPED here; it throws
Boolean A type with just two values, true and false
Enum A type with a fixed list of named values: enum DoorState { OPEN, CLOSED }
Enum with fields Enum values that carry data: UP("^") with a field arrow
Switch expression switch (x) { case A -> ...; } that produces a value; for enums it must cover every value
IllegalStateException Java's unchecked exception for "can't do that in the current state"
IllegalArgumentException Java's unchecked exception for "this argument is invalid": floor 12
Encapsulation Keeping fields private so they change only through methods that check the rules
Record A short class that just holds values, with constructor, getters, equals, hashCode, toString written by Java
Sealed interface An interface that lists exactly which classes may implement it: permits ExternalRequest, InternalRequest
Validation Checking input before using it: is the floor between 0 and 9?
Queue A line: add at the back, take from the front
FIFO First in, first out: the first request added is served first
FCFS First come, first served: the same idea as FIFO, used for scheduling
Request queue The queue of requests waiting for the car
ArrayDeque Java's fast array-based queue; add, peek, poll
peek / poll Look at the front without removing it / remove and return the front; both give null if empty
LinkedHashSet A set that keeps insertion order and refuses duplicates
Scheduling Choosing the order in which requests are served (part 2)
Tick One small step of simulated time: one floor, or one door action
Simulation Running a model step by step instead of in real time, so results are repeatable
Composition (UML) A part that lives and dies with its whole: a building's floors
Realization (UML) A class implementing an interface: InternalRequest realizes Request

Summary

  • Requirements first: call with UP/DOWN, choose a floor, move, stop, doors, display; safety: never move with the door open. Several cars and scheduling are part 2.
  • The nouns became entities: Building, Floor, ElevatorCar (the cabin, not the whole "elevator"), Button, Display, Request.
  • Three booleans let the car move with the door open (DANGER: moving with the door open!): 8 combinations, no rule.
  • Enums Direction, ElevatorState, DoorState and a state machine (go(), a switch over the current state) refuse wrong moves: can't move: door is OPEN, can't open: car is MOVING.
  • External requests (hall calls) carry floor + direction; internal requests (car calls) carry the destination; both are records behind a sealed interface. Buttons only make requests; the building validates floors (no floor 12 in a 10-floor building).
  • The request queue (FIFO, ArrayDeque) served 5, 1, 6, 2 in 18 floors instead of 6: the order needs scheduling.
  • The car runs in ticks: one action per step(), repeatable and testable.

Next episode: Design an Elevator System, part 2: FCFS, SCAN, LOOK, shortest seek time, a dispatcher and many elevators.