These are the notes for Low-Level Design (LLD) episode 19: UML behaviour diagrams. Last episode's class diagram showed what exists. Today's four diagrams show what happens: the sequence diagram (who calls whom, in what order), the use-case diagram (who uses the system, for what), the activity diagram (the steps of a workflow) and the state machine diagram (the life of one object). Every program was actually run with javac Main.java && java -cp . Main (Java 21); outputs and error messages are real.
1. The real-life problem: a team sheet can't tell the story
A cricket team sheet lists eleven players: who bats, who bowls. It tells you who exists. Ask it "who bowled the last over, and what happened on the fifth ball?" and it has no idea: it has no order and no events. For that you need ball-by-ball commentary: what happened, in order.
A class diagram is a team sheet. It shows classes, fields, operations and relationships. It does not show in what order things may happen.
2. The problem in code: delivered, never paid
A food delivery app's Order was coded straight from a correct class diagram with two operations, pay() and deliver():
class Order { // the class diagram: pay(), deliver()
final int id;
boolean paid, delivered;
Order(int id) { this.id = id; }
void pay() { paid = true; }
void deliver() { delivered = true; }
}
public class Main {
public static void main(String[] args) {
Order o = new Order(17);
o.deliver(); // nothing says pay comes first
System.out.println("Order " + o.id + " delivered: " + o.delivered
+ ", paid: " + o.paid);
}
}
Order 17 delivered: true, paid: false
It compiled, it ran, and the class diagram allowed it. Free food. A class diagram says which operations exist, not which order they are allowed in. We need diagrams of behaviour.
3. UML's other half: behaviour diagrams
UML (Unified Modeling Language, episode 18) defines 14 diagram types in UML 2:
| Group | Diagrams | Shows |
|---|---|---|
| Structure diagrams (7) | class, object, component, composite structure, deployment, package, profile | what exists and how it connects |
| Behaviour diagrams (7) | activity, state machine, use case, and the 4 interaction diagrams below | what happens over time |
| Interaction diagrams (a subset of behaviour) | sequence, communication, interaction overview, timing | objects talking to each other: the flow of control and data |
Four of them cover almost everything you need in LLD interviews:
| Diagram | Question it answers | Real-life example |
|---|---|---|
| Sequence | Who calls whom, in what order? | a phone-call log |
| Use case | Who uses the system, and for what? | who visits a bank branch and why |
| Activity | What are the steps of a workflow? | a chai recipe |
| State machine | What can happen to one object over its life? | a train ticket: WL → RAC → CNF |
4. Sequence diagrams
4.1 Start from a real call trace
A customer places an order. The app charges the payment service, then asks the restaurant to confirm. Each call prints a line, indented by how deep it is in the call chain:
class Payment {
boolean charge(int amt) { System.out.println(" Payment: charge Rs " + amt); return true; }
}
class Restaurant {
void confirm(String item) { System.out.println(" Restaurant: confirm " + item); }
}
class App {
Payment pay = new Payment();
Restaurant rest = new Restaurant();
String placeOrder(String item, int amt) {
System.out.println(" App: placeOrder(" + item + ")");
if (!pay.charge(amt)) return "failed";
rest.confirm(item);
return "confirmed";
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Customer: " + new App().placeOrder("Masala Dosa", 120));
}
}
App: placeOrder(Masala Dosa)
Payment: charge Rs 120
Restaurant: confirm Masala Dosa
Customer: confirmed
The customer's line is printed last, because the customer waits for placeOrder to return. That trace is a story in time; a sequence diagram draws it.
4.2 The parts of a sequence diagram
Customer :App :Payment :Restaurant
| | | |
|placeOrder(dosa)| | |
|---------------># | |
| # charge(120) | |
| #----------------># |
| # true # |
| #<- - - - - - - - # |
| # confirm(dosa) |
| #---------------------------------->#
| # done #
| #<- - - - - - - - - - - - - - - - - #
| "confirmed" # | |
|<- - - - - - - -# | |
| SMS: order placed (async) | |
|<---------------# | |
| Part | Drawn as | Meaning | Example |
|---|---|---|---|
| Participant | a box at the top | an object or actor taking part. :App means "an object of class App" |
:Payment |
| Lifeline | a dashed vertical line under the box | the participant's existence over time; time flows downwards | the line under :App |
| Synchronous message | solid line, filled arrowhead | a call where the caller waits for the answer; a normal Java method call | charge(120) |
| Return message | dashed line, open arrowhead | the answer coming back, labelled with the value | true, "confirmed" |
| Asynchronous message | solid line, open arrowhead | the caller sends and does not wait | SMS: order placed |
| Activation bar (execution specification) | a thin box on a lifeline | the time that object is busy executing | :Payment is busy only while charging |
| Self-message | an arrow looping back to the same lifeline | an object calling its own method | add price |
Real-life example for sync vs async: a phone call is synchronous (you hold the line until they answer); a text message is asynchronous (you send it and carry on; the reply comes whenever). In Java, a plain method call is synchronous; handing work to a queue, a thread or a notification service is asynchronous.
Return messages are optional in UML; draw them when the returned value matters to the story.
4.3 Combined fragments: alt, opt and loop
Real flows have ifs and loops. Here the app adds up a price per item in a loop, then charges; if the payment is declined it returns early, otherwise the restaurant confirms. The wallet holds Rs 200:
class Payment {
int balance = 200;
boolean charge(int amt) {
System.out.println(" Payment: Rs " + amt + (amt <= balance ? " ok" : " declined"));
return amt <= balance;
}
}
class App {
Payment pay = new Payment();
String placeOrder(String[] items) {
int total = 0;
for (String item : items) total += item.equals("Thali") ? 250 : 60; // loop
if (!pay.charge(total)) return "payment declined"; // alt [declined]
System.out.println(" Restaurant: confirm " + items.length + " items"); // alt [ok]
return "confirmed";
}
}
public class Main {
public static void main(String[] args) {
App app = new App();
System.out.println("Customer: " + app.placeOrder(new String[]{"Idli", "Vada"}));
System.out.println("Customer: " + app.placeOrder(new String[]{"Thali"}));
}
}
Payment: Rs 120 ok
Restaurant: confirm 2 items
Customer: confirmed
Payment: Rs 250 declined
Customer: payment declined
Same method, two different paths: in the second order the restaurant is never called. A sequence diagram shows this with combined fragments: a box around some messages, with an operator in the corner tab and a guard in square brackets.
| Fragment | Java equivalent | Meaning | Example guard |
|---|---|---|---|
loop |
for / while |
repeat the messages inside | [for each item] |
alt |
if / else (or switch) |
alternatives: the box is split by dashed lines into regions, one per branch; exactly one region runs | [charge ok] / [declined] |
opt |
if with no else |
the messages run only if the guard is true | [customer tips] |
A guard is a condition written in square brackets: the part of the diagram it labels happens only when the condition is true. Other operators exist (par for parallel, break, critical), but alt, opt and loop are the ones you'll use daily.
:App :Payment :Restaurant
| ┌ loop [for each item] ┐
|──┤ add price (self) │
| └──────────────────────┘
|──── charge(total) ──────▶|
┌ alt [charge ok] ─────────────────────────────────────┐
│ |──────────── confirm(items) ──────────────────────▶ │
├ - - - - - - - - - - - - - - - - - - - - - - - - - - -┤
│ [declined] "payment declined" returned to Customer │
└──────────────────────────────────────────────────────┘
5. Use-case diagrams
Real-life example: a bank branch. People walk in as account holders (a role, not a particular person: you could be an account holder today and a loan applicant tomorrow). Each comes with a goal: deposit cash, open an account. The branch walls mark what the bank is responsible for.
| Term | Drawn as | Meaning | Food app example |
|---|---|---|---|
| Actor | a stick figure outside the boundary | a role played by a person or by another system that uses the system | Customer, Delivery partner, Restaurant, Payment gateway |
| Use case | an oval inside the boundary | a goal the system helps an actor achieve, named verb + noun | Place order, Track order |
| System boundary | a big rectangle | what the system is responsible for | "Food delivery app" |
| Association | a plain line | the actor takes part in that use case | Customer — Place order |
| «include» | dashed arrow from the base use case to the included one | the included behaviour always happens as part of the base | Place order ┄«include»┄▶ Pay |
| «extend» | dashed arrow from the optional use case to the base | optional behaviour that sometimes adds to the base | Apply coupon ┄«extend»┄▶ Place order |
┌──────────── Food delivery app ────────────┐
│ │
Customer ─────┼──( Place order )┄┄«include»┄┄▶( Pay )─────┼──── Payment gateway
\ │ ▲ │
\ │ «extend» │
\ │ ( Apply coupon ) ( Accept order )──┼──── Restaurant
\──────┼──( Track order ) │
Delivery ───────┼──────────────────────( Deliver order ) │
partner └───────────────────────────────────────────┘
Memory trick: include = always, extend = sometimes. And note the arrow directions: include points to the included piece; extend points to the base it extends.
A use-case diagram is a map, not a spec: each oval is usually backed by a short text description (main flow and alternate flows), which episode 20 covers.
6. Activity diagrams
Real-life example: making chai. Boil water, add tea leaves (steps in order). No milk? Make black tea (a choice). Grate ginger while the water boils (two things at once). Mum boils, you serve (who does which step).
| Term | Drawn as | Meaning |
|---|---|---|
| Initial node | a filled black dot | where the flow starts |
| Action | a rounded rectangle | one step of work. "Take payment" |
| Control flow | an arrow | what comes next |
| Decision | a diamond with guarded arrows out | choose exactly one path; guards must not overlap. [yes] / [no] |
| Merge | a diamond with several arrows in, one out | brings alternative paths back together |
| Fork | a thick bar, one arrow in, several out | split into parallel paths |
| Join | a thick bar, several arrows in, one out | wait until all parallel paths are done |
| Activity final node | a dot inside a ring (bullseye) | the whole flow ends |
| Swimlane (partition) | a lane per actor or department | shows who does each action |
The order workflow from the video:
Customer | (●) → [Choose dishes] ←──────────── [See "sold out"]
| │ ▲ [no]
App | └──▶ <stock?> ─[yes]─▶ [Take payment] ─▶ ┃ fork ┃ ─▶ [Assign a rider] ─▶ ┃ join ┃ ─▶ (◉)
Restaurant | ┃ ┃ ─▶ [Cook the food] ─▶ ┃ ┃
An activity diagram is a flowchart that also understands parallel work (fork/join) and responsibility (swimlanes). Use it for business workflows: checkout, refunds, onboarding.
7. State machine diagrams
Real-life example: an Indian Railways ticket. At any moment it is in exactly one status: WL (waitlisted), RAC (reservation against cancellation: partly confirmed, a shared berth), CNF (confirmed). Someone else cancelling moves it up; a cancelled ticket can never become confirmed.
| Term | Drawn as | Meaning | Order example |
|---|---|---|---|
| State | rounded rectangle | a condition the object is in, for a while | PAID |
| Initial state (pseudostate) | filled dot with an arrow | where the object's life starts | → PLACED |
| Final state | dot in a ring | the life is over | after DELIVERED or CANCELLED |
| Event | the label on a transition | something that happens and may cause a change | pay, cook, cancel |
| Transition | an arrow between states | an allowed move from one state to another, fired by an event | PAID --cook--> PREPARING |
| Guard | [condition] after the event |
the transition fires only if the condition is true | pay [amount > 0] |
| Self-transition | an arrow looping back to the same state | the event is handled but the state does not change | edit address on PLACED |
The full label syntax is event [guard] / action, e.g. pay [amount > 0] / sendReceipt.
(●) ─▶ PLACED ──pay [amount > 0]──▶ PAID ──cook──▶ PREPARING ──dispatch──▶ OUT_FOR_DELIVERY
│ ↺ edit address │ │ deliver
│ cancel │ cancel ▼
└──────────▶ CANCELLED ◀─────┘ DELIVERED
│ │
▼ ▼
(◉) (◉)
The key insight: there is no arrow from PLACED to DELIVERED, so delivering an unpaid order is not allowed. The diagram contains exactly the rule our first program was missing.
7.1 The fix in code: an enum state machine
Each state becomes an enum constant, each arrow becomes one method, and a single private move method rejects any event that has no arrow from the current state:
enum Status { PLACED, PAID, PREPARING, OUT_FOR_DELIVERY, DELIVERED }
class Order {
final int id;
Status status = Status.PLACED; // the initial state
Order(int id) { this.id = id; }
private void move(Status from, Status to, String event) {
String bad = "cannot " + event + " order " + id + " in state " + status;
if (status != from) throw new IllegalStateException(bad); // no arrow from here
System.out.println(event + ": " + status + " -> " + to);
status = to;
}
void pay() { move(Status.PLACED, Status.PAID, "pay"); }
void cook() { move(Status.PAID, Status.PREPARING, "cook"); }
void dispatch() { move(Status.PREPARING, Status.OUT_FOR_DELIVERY, "dispatch"); }
void deliver() { move(Status.OUT_FOR_DELIVERY, Status.DELIVERED, "deliver"); }
}
public class Main {
public static void main(String[] args) {
Order a = new Order(18);
a.pay(); a.cook(); a.dispatch(); a.deliver();
new Order(17).deliver();
}
}
pay: PLACED -> PAID
cook: PAID -> PREPARING
dispatch: PREPARING -> OUT_FOR_DELIVERY
deliver: OUT_FOR_DELIVERY -> DELIVERED
Exception in thread "main" java.lang.IllegalStateException: cannot deliver order 17 in state PLACED
at Order.move(Main.java:9)
at Order.deliver(Main.java:16)
at Main.main(Main.java:22)
IllegalStateException is Java's built-in unchecked exception for "this method was called at a bad time for the object's current state", which is exactly our situation. The missing arrow became a loud crash instead of free food. Failing loudly is a feature: the bug is found in testing, not by the accountant.
Recipe: state diagram → Java
- List the states as an
enum; the initial state is the field's starting value. - Each event becomes a public method.
- Each method calls one guarded
move(from, to)(or looks up a transition table). - No arrow? Throw
IllegalStateException. - Guards become extra
ifchecks before the move.
8. Which diagram when?
| You want to show | Draw |
|---|---|
| who uses the system, and for what | use-case diagram |
| the steps of a business workflow, with choices and parallel work | activity diagram |
| who calls whom, in what order, for one scenario | sequence diagram |
| everything that can happen to one object with a status field | state machine diagram |
| what exists and how it connects | class diagram (episode 18) |
In a machine-coding or design interview: list the use cases first, sketch the classes, then draw one sequence diagram for the trickiest flow. If an object has a status field (order, ticket, lift, parcel), draw its state machine too: it usually reveals missing rules.
Common mistakes
| Mistake | Exact message / symptom | Why | Fix |
|---|---|---|---|
o.deliver(); before pay() |
Order 17 delivered: true, paid: false |
The order of calls was never modelled | A state machine with guarded transitions |
new Order(17).deliver(); on the state machine |
IllegalStateException: cannot deliver order 17 in state PLACED |
No arrow from PLACED to DELIVERED |
Follow the transitions: pay, cook, dispatch, deliver |
| Filled arrowhead for a fire-and-forget SMS | no error: a misleading diagram | Filled = the caller waits | Open arrowhead for asynchronous messages |
«include» for an optional coupon |
no error: wrong meaning | include = always | «extend» for sometimes |
Overlapping guards on a decision, e.g. [amount > 100] and [amount > 50] |
no error: ambiguous flow | Exactly one path must be taken | Make guards mutually exclusive: [> 100], [<= 100] |
| Drawing every method call in one giant sequence diagram | unreadable diagram | One diagram should tell one scenario | One sequence diagram per important scenario |
| Putting user-interface steps as use cases ("Click button") | a diagram of screens, not goals | A use case is a goal | Name use cases verb + noun: "Place order" |
Mini project: a parcel's life
Model a courier parcel: BOOKED → PICKED_UP → IN_TRANSIT → DELIVERED, with cancel allowed only while BOOKED, returnToSender allowed while IN_TRANSIT, and a guard: delivery succeeds only on the second attempt (the first time nobody is home, a self-transition). Draw the state machine, then code it with a transition table.
(●) → BOOKED ─pickUp─▶ PICKED_UP ─ship─▶ IN_TRANSIT ─deliver [2nd attempt]─▶ DELIVERED → (◉)
│ cancel │ ↺ deliver [1st attempt]
▼ │ returnToSender
CANCELLED → (◉) ▼
RETURNED → (◉)
Solution
import java.util.*;
enum ParcelState { BOOKED, PICKED_UP, IN_TRANSIT, DELIVERED, RETURNED, CANCELLED }
class Parcel {
// the state diagram as a transition table: state -> (event -> next state)
private static final Map<ParcelState, Map<String, ParcelState>> NEXT = new EnumMap<>(ParcelState.class);
static {
NEXT.put(ParcelState.BOOKED, Map.of("pickUp", ParcelState.PICKED_UP, "cancel", ParcelState.CANCELLED));
NEXT.put(ParcelState.PICKED_UP, Map.of("ship", ParcelState.IN_TRANSIT));
NEXT.put(ParcelState.IN_TRANSIT, Map.of("deliver", ParcelState.DELIVERED, "returnToSender", ParcelState.RETURNED));
}
final String id;
private ParcelState state = ParcelState.BOOKED;
private int attempts = 0;
Parcel(String id) { this.id = id; }
void fire(String event) {
ParcelState to = NEXT.getOrDefault(state, Map.of()).get(event);
if (to == null) throw new IllegalStateException(id + ": '" + event + "' not allowed in " + state);
if (event.equals("deliver") && ++attempts < 2) { // guard: [second attempt]
System.out.println(id + ": nobody home, attempt " + attempts + " (stays " + state + ")");
return; // self-transition
}
System.out.println(id + ": " + state + " --" + event + "--> " + to);
state = to;
}
}
public class Main {
public static void main(String[] args) {
Parcel p = new Parcel("P-101");
for (String e : List.of("pickUp", "ship", "deliver", "deliver")) p.fire(e);
Parcel q = new Parcel("P-102");
q.fire("cancel");
try { q.fire("ship"); } catch (IllegalStateException ex) { System.out.println("Rejected -> " + ex.getMessage()); }
}
}
Output:
P-101: BOOKED --pickUp--> PICKED_UP
P-101: PICKED_UP --ship--> IN_TRANSIT
P-101: nobody home, attempt 1 (stays IN_TRANSIT)
P-101: IN_TRANSIT --deliver--> DELIVERED
P-102: BOOKED --cancel--> CANCELLED
Rejected -> P-102: 'ship' not allowed in CANCELLED
The Map<state, Map<event, next state>> is the diagram: one entry per arrow. A missing entry means a missing arrow, which is rejected. EnumMap (episode 3) is a fast map keyed by an enum.
Practice
1. Draw a sequence diagram for an ATM cash withdrawal: Customer, :ATM, :Bank, :CashDispenser. Include an alt for insufficient balance.
Answer
Customer → :ATM insertCard(), enterPin(pin), withdraw(2000) (synchronous)
:ATM → :Bank debit(account, 2000)
alt [balance ok]
:Bank ┄┄▶ :ATM true (return)
:ATM → :CashDispenser dispense(2000)
:ATM ┄┄▶ Customer "take your cash"
[insufficient]
:Bank ┄┄▶ :ATM false
:ATM ┄┄▶ Customer "insufficient balance"
:ATM →(async) :Bank sendSmsAlert() (open arrowhead)
2. In a library system, is "Pay fine" «include» or «extend» of "Return book"?
Answer
«extend»: a fine is paid only sometimes (when the book is late). Arrow: Pay fine ┄«extend»┄▶ Return book.
3. Which UML diagram would you draw for: (a) the life of a bug ticket (Open, In progress, Resolved, Closed, Reopened); (b) the refund process across Customer, Support and Finance; (c) what happens between :Cart, :Inventory and :Payment during checkout?
Answer
(a) State machine diagram. (b) Activity diagram with three swimlanes. (c) Sequence diagram.
4. Using the Order state machine above, what does Order a = new Order(18); a.pay(); a.deliver(); print?
Answer
pay: PLACED -> PAID, then IllegalStateException: cannot deliver order 18 in state PAID: there is no arrow from PAID to DELIVERED.
5. Add cancel to the Order code so that it works from PLACED or PAID only.
Answer
Add CANCELLED to the enum, then:
void cancel() {
if (status != Status.PLACED && status != Status.PAID)
throw new IllegalStateException("cannot cancel order " + id + " in state " + status);
System.out.println("cancel: " + status + " -> CANCELLED");
status = Status.CANCELLED;
}
Quick quiz
A lift can be IDLE, MOVING_UP, MOVING_DOWN or DOORS_OPEN. A call button or arriving at a floor changes what it is doing. You want to show every allowed change. Which diagram?
- A. Sequence diagram
- B. Use-case diagram
- C. Activity diagram
- D. State machine diagram
Answer
D. One object, a fixed set of states, and events that move it between them: a state machine diagram.
Interview questions
- Class diagram vs sequence diagram? A class diagram is static structure (what exists); a sequence diagram is one scenario's interactions over time (who calls whom, in what order).
- Synchronous vs asynchronous message? Synchronous: the caller waits for the reply (filled arrowhead). Asynchronous: the caller continues without waiting (open arrowhead).
- What is an activation bar? A thin rectangle on a lifeline showing when that object is executing.
- What are combined fragments? Name three. Boxes that add control flow to a sequence diagram:
alt(if/else),opt(if),loop(repeat); alsopar,break,critical. - Include vs extend? Include: behaviour that always happens as part of the base use case (arrow to the included one). Extend: optional behaviour that sometimes adds to the base (arrow to the base).
- What is an actor? Can it be a system? A role that interacts with the system from outside; yes, e.g. a payment gateway.
- Activity diagram vs state machine diagram? Activity: the steps of a process (what is being done). State machine: the conditions one object passes through (what the object is) and the events that move it.
- What is a guard? A boolean condition in square brackets; the transition or path is taken only when it's true.
- How do you implement a state machine in Java? An enum of states plus guarded transition methods, or a transition table
Map<State, Map<Event, State>>, or the State pattern (episode 37); reject invalid events withIllegalStateException. - Fork vs decision? A decision picks exactly one outgoing path; a fork starts all outgoing paths in parallel (and a join waits for all of them).
Glossary
| Term | Meaning, with an example |
|---|---|
| UML | Unified Modeling Language: the standard drawing language for software designs |
| Structure diagram | Shows what exists and how it connects. The class diagram |
| Behaviour diagram | Shows what happens over time. Sequence, use case, activity, state machine |
| Interaction diagram | A behaviour diagram about objects exchanging messages. The sequence diagram |
| Sequence diagram | Shows the messages between participants in time order for one scenario |
| Participant | An object or actor taking part in a sequence diagram. :Payment |
:ClassName |
"An object of this class" in UML. :App |
| Lifeline | The dashed vertical line under a participant; time flows downwards |
| Message | A call or signal from one lifeline to another, drawn as an arrow. charge(120) |
| Synchronous message | The caller waits for the answer; filled arrowhead. A normal method call, like a phone call |
| Asynchronous message | The caller doesn't wait; open arrowhead. An SMS notification, like a text message |
| Return message | The answer coming back; dashed arrow. true |
| Self-message | A call from an object to itself. add price |
| Activation bar | A thin box on a lifeline showing when that object is busy |
| Combined fragment | A box around messages that adds control flow: alt, opt, loop |
alt |
if / else: one region per branch, exactly one runs |
opt |
if with no else: runs only when the guard is true |
loop |
repeat the messages inside. [for each item] |
| Guard | A condition in square brackets that must be true. [charge ok], [amount > 0] |
| Use-case diagram | Shows actors, their goals (use cases) and the system boundary |
| Actor | A role (a person or another system) that uses the system from outside. Customer, Payment gateway |
| Use case | A goal the system helps an actor achieve, named verb + noun. "Place order" |
| System boundary | A rectangle marking what the system is responsible for |
«include» |
The base use case always uses the included one. Place order includes Pay |
«extend» |
An optional use case that sometimes adds to a base one. Apply coupon extends Place order |
| Activity diagram | A flowchart of a workflow with decisions, parallel paths and swimlanes |
| Action | One step in an activity diagram; a rounded box. "Take payment" |
| Control flow | An arrow showing which step comes next |
| Initial node | A filled dot: where a flow or a life starts |
| Final node | A dot inside a ring: where a flow or a life ends |
| Decision | A diamond that picks exactly one outgoing path by its guards |
| Merge | A diamond where alternative paths come back together |
| Fork | A thick bar that splits the flow into parallel paths |
| Join | A thick bar that waits for all parallel paths to finish |
| Swimlane (partition) | A lane showing who performs the actions in it. Customer, App, Restaurant |
| State machine diagram | Shows the states one object can be in and the events that move it between them |
| State | A condition an object is in for a while. PAID, a ticket's RAC |
| Initial state | Where an object's life starts. PLACED |
| Final state | Where an object's life ends. After DELIVERED |
| Event | Something that happens and may trigger a transition. pay, someone cancelling a ticket |
| Transition | An allowed move from one state to another. PAID --cook--> PREPARING |
| Self-transition | An event handled without changing state. edit address |
| Transition table | A map from (state, event) to the next state; the diagram as data |
enum |
A Java type with a fixed set of named constants (episode 3). Status.PAID |
EnumMap |
A fast Map whose keys are the constants of one enum (episode 3) |
IllegalStateException |
Java's unchecked exception for "called at the wrong time for the object's state" |
| WL / RAC / CNF | Indian Railways ticket statuses: waitlisted, reservation against cancellation, confirmed |
Summary
- A class diagram shows structure, not order: it happily allowed
deliver()beforepay(). - Sequence diagram: lifelines, synchronous (filled), asynchronous (open) and return (dashed) messages, activation bars, and
alt/opt/loopfragments with guards. - Use-case diagram: actors outside, use cases inside the system boundary; include = always, extend = sometimes.
- Activity diagram: actions, decisions with guards, fork/join for parallel work, swimlanes for who does what.
- State machine diagram: states, events, guards, transitions; no arrow = not allowed.
- A state machine turns straight into Java: an enum plus guarded transition methods that throw
IllegalStateException.
Next episode: From requirements to classes: object-oriented analysis.