State diagrams
State diagrams (UML state machines) model object lifecycles by showing states, events, transitions, guards and actions, including nested (composite) and concurrent behaviour, so engineers can specify and analyse dynamic behaviour of classes and systems.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
State diagrams are used by engineers to model the dynamic behaviour of an object or component: what it can do, how it reacts to events, and how it moves between conditions over time. They are essential when designing controllers (embedded systems), protocol handlers, UI widgets, and any object with non-trivial lifecycle — and they connect to other topics such as sequence models and activity models.
Key ideas
- Transition: a relationship from a source state to a target state that denotes movement when a specified event occurs and any guard is true. Represent as a directed arrow from source to target.
- Guard: a boolean condition that must be true for a transition to fire. It is written in square brackets after the event:
event [guard]. - Action: an operation performed when the transition fires. Written after a slash:
event [guard] / action. - Initial pseudostate: the starting point inside a state machine or composite state. Draw as a filled circle.
- Final state: denotes completion of behavior in that region. Draw as a bullseye (a small filled circle inside a larger hollow circle). Distinct from the Terminate pseudostate, drawn as a small circle with an X, which immediately aborts the entire state machine on entry.
- Composite state (nested state): a state that contains other states and transitions. Use a rounded rectangle containing its substates and include its own initial pseudostate. Composite states support information hiding and reduce clutter.
- Orthogonal regions (concurrency): partitions inside a composite state that execute concurrently (orthogonal behaviour). Draw as the composite state divided by solid lines into regions, each with its own states and initial pseudostate.
- Entry, exit and do actions: special actions associated with a state:
entry / aruns when entering,exit / bon exit, anddo / activitywhile in the state (may be interruptible). The standard execution order for a simple transition is: 1) evaluate guard on event, 2) execute exit actions of source state (from inner to outer), 3) execute transition action, 4) execute entry actions of target state (outer to inner), then start do activity of target. (Assumption: no deferred events; if events are deferred different semantics apply.) - Deferred events: events listed in a state's deferrable trigger list are queued while in that state and handled upon exit into a state that accepts them.
- History pseudostates: record the last active substate of a composite state. Shallow history (H) remembers immediate substate only. Deep history (H)* remembers nested substates recursively. When entering with history, the machine re-enters the recorded configuration rather than the initial substate.
- Fork and join: forks split control into concurrent flows; joins merge concurrent flows back into one. Use thick bars for fork and join. Fork creates simultaneous transitions into multiple orthogonal regions; join waits for all incoming transitions to complete before continuing.
- Choice and junction pseudostates: choice (decision) is a runtime conditional branching pseudostate (draw as a diamond). Junction is a routing point used for transition composition (drawn as a small filled circle; unlike the Initial, it can have multiple incoming and outgoing transitions); both affect control flow but have different semantics (choice evaluates guards at runtime; a junction composes transitions and can have guards on incoming and/or outgoing legs).
Exact formal definition (concise university style): A UML state machine M is a tuple M = (S, P, I, E, G, A, T) where
- S is a finite set of states (including composite states); pseudostates are not in S,
- P is the set of pseudostates (e.g., initial, choice, junction, history, fork/join, entry/exit, terminate), and I ⊆ P is the set of initial pseudostates (one per region in an orthogonal composite),
- E is the set of events; G is the set of guards (boolean expressions),
- T ⊆ S × (E ∪ {ε}) × G × A × S is the set of transitions, each transition t = (s_src, evt, guard, action, s_tgt), where guard ∈ G and action ∈ A,
- A is the set of actions (including entry/exit/do), with semantics: when an event evt occurs and a transition t is enabled (guard true and with highest priority by depth: innermost/nearest-source transitions override outer ones), the machine exits the source configuration up to the least common ancestor (LCA), executes the transition effect (action), then enters the target configuration from the LCA down, applying entry/do actions according to nesting and concurrency rules. If evt = ε (completion), the transition fires when the source state's internal activities complete.
What to draw (text instructions for diagrams):
- For a simple state machine draw an initial filled circle, states as rounded rectangles, directed arrows for transitions, and a final state marker for termination.
- For a composite state draw a rounded rectangle that contains its own initial pseudostate (small filled circle), substates and transitions. If concurrent, partition the rectangle into vertical or horizontal regions with a solid line; put an initial pseudostate into each region.
- Label each transition:
event [guard] / action. If no guard, omit brackets; if no action, omit slash and action; if there is no event (a completion transition), start the label with the guard or just/ action.
Assumptions behind these rules: these describe UML state machine notation and commonly taught semantics; tool-specific details (e.g., event queueing policy or semantics of deferred events) can vary by UML profile or tool.
Formulas
transition-label ::= event [guard] / action — syntax to remember: an optional event, optional guard in square brackets, and optional action after slash.
entry / action — action executed on entering a state.
exit / action — action executed on exit of a state.
do / activity — activity executed while in the state.
history: H or H* — shallow (H) or deep (H*) history pseudostate.
composite state { region1 | region2 | ... } — orthogonal regions run concurrently.
(These are notation rules rather than mathematical formulas; use them when writing transition labels and building diagrams.)
Worked examples
Example 1 — ATM session (model answer) Task: Draw a state diagram for a simplified ATM focusing on the card and pin flow. States: Idle, CardInserted, Authenticated, Selecting, Processing, Ejecting, OutOfService. Transitions and labels (draw arrows and label exactly):
- Initial -> Idle.
- Idle -> CardInserted:
cardInserted / captureCard. - CardInserted -> Idle:
timeout [pinRetries == 0] / ejectCard; retainCard(if retries exhausted). - CardInserted -> Authenticated:
pinEntered [pinCorrect] / openSession. - CardInserted -> CardInserted:
pinEntered [not pinCorrect] / pinRetries = pinRetries - 1(self transition). - Authenticated -> Selecting:
sessionStarted / displayMenu. - Selecting -> Processing:
selectWithdraw [balance >= amount] / dispenseCash. - Processing -> Ejecting:
cashDispensed / printReceipt. - Ejecting -> Idle:
cardEjected / resetSession. Also include transition from any state to OutOfService onmachineFault / notifyAdminand a final state inside OutOfService if required. Step-by-step trace (numbers):
- Event:
cardInsertedtriggers Idle -> CardInserted; actioncaptureCardruns. 2) Event:pinEnteredwith wrong pin; guard false for correct, self transition executes reducingpinRetries. 3) After correct pin,pinEnteredfires with guard true; exit CardInserted actions (if any), transition actionopenSessionexecutes, entry of Authenticated runs. Final answer expected: diagram with states, transitions labelled exactly as above, plus short narrative of event sequence.
Example 2 — Traffic light with pedestrian crossing (concurrency)
Task: Show vehicle-light and pedestrian-light as orthogonal regions inside a composite state IntersectionController.
Draw a composite rounded rectangle named IntersectionController, partition vertically into two regions: left region VehicleLight with states Green, Yellow, Red; right region PedestrianLight with states Walk, FlashingDontWalk, DontWalk. Put initial pseudostate into each region and transitions for normal timing. Add a buttonPressed event in Pedestrian region that triggers a choice pseudostate to wait until VehicleLight is Red before allowing Walk. Describe synchronization: vehicle region runs timers independently; pedestrian Walk transition uses join/fork semantics to ensure safe crossing.
Step-by-step trace: 1) both regions start at their initial states (Vehicle=Green, Pedestrian=DontWalk). 2) buttonPressed stores request. 3) when Vehicle transitions to Red, the Guard [requestPending] allows Pedestrian to go to Walk. 4) After Walk time, both regions resume normal cycles.
Example 3 — Deep versus shallow history (explain) Draw a composite state Player with substates Stopped and Playing; Playing contains substates Paused and Running; Running contains subtasks like Fast and Normal. Use H* inside Player. Show sequence: enter Player initially -> Stopped, then transition to Playing -> Running -> Normal. If later transition out and re-enter Player via H* the machine restores Playing->Running->Normal (deep history). If H used (shallow) only Playing is restored and re-entry goes to its initial or last immediate substate but not deeper levels.
Common mistakes
- Wrong ordering of exit/transition/entry actions: universities expect exit actions before transition action and entry actions after it (describe this order in answers).
- Forgetting initial pseudostates inside composite or orthogonal regions — results in incomplete diagrams.
- Treating history H as deep history: H is shallow (only immediate substates) while H* is deep; students often swap them.
- Using fork/join as simple branching without understanding join waits for all incoming flows.
- Mixing activity diagram notation (flows) with state machine notation (states/transitions) — these are different UML diagrams.
- Confusing self-transitions with internal transitions: a self-transition exits and re-enters the state (entry/exit run), whereas an internal transition handles the event without leaving the state.
For your exam
Typical question types: definitions (define state, transition, event, guard, action), sketch and label a state diagram, derive behaviour from a diagram (trace events), convert a textual description to a state diagram, explain nested or concurrent behaviour, compare shallow and deep history. What full-marks answers include:
- Clear, neatly drawn diagram with initial and final pseudostates, states as rounded rectangles, transition arrows labelled exactly
event [guard] / action. - Correct use of composite states and orthogonal regions when concurrency is required.
- Explanation of the execution order (exit actions -> transition action -> entry actions) and handling of do/entry/exit actions where relevant.
- For trace questions, step-by-step event processing listing guards, actions executed, and final state configuration.
- When asked to compare shallow and deep history give both semantic effect and example.
Quick check
- How do you write a transition that fires on event pay when amount >= price and then calls dispense?
- What does a shallow history pseudostate remember?
- In which order are exit actions, transition action and entry actions executed on a transition?
Answers: 1)pay [amount >= price] / dispense2) Immediate (one-level) last active substate of the composite (does not restore nested substates) 3) Exit actions of source (inner to outer) -> transition action -> entry actions of target (outer to inner).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?