UML State Machine Diagrams
Detailed description
UML state machine diagram with 6 states (Created, Paid, Shipped, Delivered, Cancelled, Refunded). Transitions: the initial pseudostate transitions to Created on Order Placed by Customer; Created transitions to Paid on payment_received; Paid transitions to Shipped on item_dispatched; Shipped transitions to Delivered on delivery_confirmed; Created transitions to Cancelled on customer_cancels / payment_timeout; Paid transitions to Refunded on return_initiated; Delivered transitions to the final state; Cancelled transitions to the final state; Refunded transitions to the final state.
States
- Created
- Paid
- Shipped
- Delivered
- Cancelled
- Refunded
Transitions
- the initial pseudostate transitions to Created on Order Placed by Customer
- Created transitions to Paid on payment_received
- Paid transitions to Shipped on item_dispatched
- Shipped transitions to Delivered on delivery_confirmed
- Created transitions to Cancelled on customer_cancels / payment_timeout
- Paid transitions to Refunded on return_initiated
- Delivered transitions to the final state
- Cancelled transitions to the final state
- Refunded transitions to the final state
UML State Machine Diagrams
🎯 Learning Objectives
By the end of this chapter, you will be able to:
- Identify the core components of a UML State Machine diagram (states, transitions, events, guards, and effects).
- Translate a behavioral description of a system into a syntactically correct ASCII state machine diagram.
- Evaluate when to use state machines versus other behavioral diagrams (like sequence or activity diagrams) in the software design process.
🧠 Activating Prior Knowledge
Before we dive into the formal UML syntax, let’s connect this to something you already know. Think about a standard vending machine. You can’t just press the “Dispense” button and expect a snack if you haven’t inserted money first. The machine has different conditions of being—it is either “Waiting for Money”, “Waiting for Selection”, or “Dispensing”.
In software engineering, we call these conditions States. The rules that dictate how the machine moves from one condition to another are called Transitions. If you have ever written a switch statement or a complex if-else block to manage what an application should do based on its current status, you have informally programmed a state machine.
1. Introduction: Why State Machines?
Software objects rarely react to the exact same input in the exact same way every time. Their response depends on their current context or state.
UML State Machine diagrams provide a visual, rigorous way to model this lifecycle. They are particularly useful for:
- Embedded systems and hardware controllers.
- UI components (e.g., a button that toggles between ‘Play’ and ‘Pause’).
- Game entities and AI behaviors.
- Complex business objects (e.g., an Order that moves from Pending -> Paid -> Shipped).
To manage cognitive load, we will break down the state machine into its smallest atomic parts before looking at a complete, complex system.
2. The Core Elements
2.1 States
A State represents a condition or situation during the life of an object during which it satisfies some condition, performs some activity, or waits for some event.
- Initial State : The starting point of the machine, represented by a solid black circle.
- Regular State : Represented by a rectangle with rounded corners.
- Final State : The end of the machine’s lifecycle, represented by a solid black circle surrounded by a hollow circle (a bullseye).
2.2 Transitions
A Transition is a directed relationship between two states. It signifies that an object in the first state will enter the second state when a specified event occurs and specified conditions are satisfied.
Transitions are labeled using the following syntax:
Event [Guard] / Effect
- Event: The trigger that causes the transition (e.g.,
buttonPressed). - Guard: A boolean condition that must be true for the transition to occur (e.g.,
[powerLevel > 10]). - Effect: An action or behavior that executes during the transition (e.g.,
/ turnOnLED()).
2.3 Internal Activities
States can have internal activities that execute at specific points during the state’s lifetime. These are written inside the state rectangle:
entry /— An action that executes every time the state is entered.exit /— An action that executes every time the state is exited.do /— An ongoing activity that runs while the object is in this state.
Detailed description
UML state machine diagram with 2 states (Idle, Processing). Transitions: the initial pseudostate transitions to Idle on powerOn(); Idle transitions to Processing on requestReceived / logRequest(); Processing transitions to Idle on complete; Processing transitions to the final state on fatalError / shutDown().
States
- Idle
- Processing
Transitions
- the initial pseudostate transitions to Idle on powerOn()
- Idle transitions to Processing on requestReceived / logRequest()
- Processing transitions to Idle on complete
- Processing transitions to the final state on fatalError / shutDown()
Internal activities are particularly useful for modeling embedded systems, UI components, and any object that needs to perform setup/teardown when entering or leaving a state.
Quick Check (Retrieval Practice): What is the difference between an
entry/action and an effect on a transition (the/ actionpart ofEvent [Guard] / Effect)? Think about when each executes. The entry action runs every time the state is entered regardless of which transition was taken, while the transition effect runs only during that specific transition.
2.4 Composite States (Advanced)
A composite state is a state that contains a nested state machine inside it. Hierarchical (composite) states originate in Harel’s statecharts (1987) and were already present in UML 1.x; UML 2 formalized and extended their semantics to avoid the “spaghetti” of a flat state machine with dozens of transitions. When an object is in a composite state, it is simultaneously in exactly one of the nested substates.
Example: A downloadable video has a high-level Active state that contains substates Buffering, Playing, and Paused. From any substate, a stop() event exits the entire composite state.
This avoids drawing stop transitions from every leaf state separately — one transition at the composite level covers all of them. The UML 2 Reference Manual (Rumbaugh et al.) describes composite states as the primary tool for managing state-machine complexity.
2.5 Choice Pseudostate (Advanced)
A choice pseudostate (drawn as a small diamond, <>) is a branch point where the next state depends on a runtime condition evaluated inside the transition. Use it when a single event could lead to several outcomes and the decision belongs on the transition rather than in the state itself.
Compare to guards: A guard is evaluated before the transition fires; a choice pseudostate is evaluated during the transition, after some computation has happened. In most introductory models, guards are sufficient — reach for the choice pseudostate only when the branching logic is non-trivial.
3. Case Study: Modeling an Advanced Exosuit
To see how these pieces fit together, let’s model the core power and combat systems of an advanced, reactive robotic exosuit (akin to something you might see flying around in a cinematic universe).
When the suit is powered on, it enters an Idle state. If its sensors detect a threat, it shifts into Combat Mode, deploying repulsors. However, if the suit’s arc reactor drops below 5% power, it must immediately override all systems and enter Emergency Power mode to preserve life support, regardless of whether a threat is present.
Detailed description
UML state machine diagram with 3 states (Idle, CombatMode, EmergencyPower). Transitions: the initial pseudostate transitions to Idle on powerOn(); Idle transitions to CombatMode on threatDetected [sysCheckOK] / deployUI(); CombatMode transitions to Idle on threatNeutralized / retractWeapons(); CombatMode transitions to EmergencyPower on [powerLevel < 5%] / rerouteToLifeSupport(); EmergencyPower transitions to the final state on manualOverride().
States
- Idle
- CombatMode
- EmergencyPower
Transitions
- the initial pseudostate transitions to Idle on powerOn()
- Idle transitions to CombatMode on threatDetected [sysCheckOK] / deployUI()
- CombatMode transitions to Idle on threatNeutralized / retractWeapons()
- CombatMode transitions to EmergencyPower on [powerLevel < 5%] / rerouteToLifeSupport()
- EmergencyPower transitions to the final state on manualOverride()
Deconstructing the Model
- The Initial Transition: The system begins at the solid circle and transitions to
Idlevia thepowerOn()event. - Moving to Combat: To move from
IdletoCombat Mode, thethreatDetectedevent must occur. Notice the guard[sysCheckOK]; the suit will only enter combat if internal systems pass their checks. As the transition happens, the effect/ deployUI()occurs. - Cyclic Behavior: The system can transition back to
Idlewhen thethreatNeutralizedevent occurs, triggering the/ retractWeapons()effect. - Critical Transitions: The transition to
Emergency Poweris a completion transition guarded by[powerLevel < 5%]— it has no explicit event trigger and fires as soon as the guard becomes true while the source state is settled. Notice the brackets: per the UML 2.5.1 transition-label syntaxEvent [Guard] / Effect, the guard must always appear in square brackets so it is not misread as an event name. Once in this state, the only way out is amanualOverride(), leading to the Final State (system shutdown).
Real-World Examples
The exosuit above introduces the syntax. Now let’s see state machines applied to three modern systems. Each example highlights a different aspect of state machine design.
Example 1: Spotify — Music Player States
Scenario: A track player has distinct states that determine how it responds to the same button press. Pressing play does nothing when you are already playing — but it transitions correctly from Paused or Idle. This context-dependence is exactly what state machines model.
Detailed description
UML state machine diagram with 4 states (Idle, Buffering, Playing, Paused). Transitions: the initial pseudostate transitions to Idle on appLaunch(); Idle transitions to Buffering on playTrack(trackId); Buffering transitions to Playing on bufferReady; Buffering transitions to Idle on loadError / showErrorMessage(); Playing transitions to Paused on pauseButton; Paused transitions to Playing on playButton; Playing transitions to Buffering on skipTrack(nextId) / clearBuffer(); Playing transitions to Idle on stopButton.
States
- Idle
- Buffering
- Playing
- Paused
Transitions
- the initial pseudostate transitions to Idle on appLaunch()
- Idle transitions to Buffering on playTrack(trackId)
- Buffering transitions to Playing on bufferReady
- Buffering transitions to Idle on loadError / showErrorMessage()
- Playing transitions to Paused on pauseButton
- Paused transitions to Playing on playButton
- Playing transitions to Buffering on skipTrack(nextId) / clearBuffer()
- Playing transitions to Idle on stopButton
Reading the diagram:
Bufferingas a transitional state: When a track is requested, the player cannot play immediately — it must buffer first. The guard-free transitionbufferReadyfires automatically when enough data has loaded.- Error handling via effect: If loading fails,
loadErrorfires and the effect/ showErrorMessage()executes before returning toIdle. One transition handles the rollback and the user feedback. skipTrackresets the buffer: Skipping while playing triggers/ clearBuffer()as a transition effect, moving back toBufferingfor the new track. Making side effects explicit in the diagram (rather than hiding them in code comments) is a key UML best practice.- No final state: A music player runs indefinitely — there is no lifecycle end for this object. Omitting the final state is the correct choice here, not an oversight.
Example 2: GitHub — Pull Request Lifecycle
Scenario: A pull request moves through a well-defined set of states from creation to merge or closure. Guards prevent premature merging — merging broken code has real consequences in a real system.
Detailed description
UML state machine diagram with 5 states (Open, ChangesRequested, Approved, Merged, Closed). Transitions: the initial pseudostate transitions to Open on createPR(); Open transitions to ChangesRequested on reviewSubmitted [hasRejection]; ChangesRequested transitions to Open on pushNewCommit; Open transitions to Approved on reviewSubmitted [allApproved] / notifyAuthor(); Approved transitions to Merged on mergePR [ciPassed] / closeHeadBranch(); Open transitions to Closed on closePR(); ChangesRequested transitions to Closed on closePR(); Merged transitions to the final state; Closed transitions to the final state.
States
- Open
- ChangesRequested
- Approved
- Merged
- Closed
Transitions
- the initial pseudostate transitions to Open on createPR()
- Open transitions to ChangesRequested on reviewSubmitted [hasRejection]
- ChangesRequested transitions to Open on pushNewCommit
- Open transitions to Approved on reviewSubmitted [allApproved] / notifyAuthor()
- Approved transitions to Merged on mergePR [ciPassed] / closeHeadBranch()
- Open transitions to Closed on closePR()
- ChangesRequested transitions to Closed on closePR()
- Merged transitions to the final state
- Closed transitions to the final state
Reading the diagram:
- Guards on the same event: Both
Open → ChangesRequestedandOpen → Approvedare triggered byreviewSubmitted. The guards[hasRejection]and[allApproved]select which transition fires. The same event can lead to different states — the guard is the deciding factor. - Cyclic path (ChangesRequested → Open): After a reviewer requests changes, the author pushes new commits, sending the PR back to
Open. State machines can loop — objects do not always progress linearly. - Guard on merge (
[ciPassed]): The PR staysApproveduntil CI passes. This is a business rule — it cannot be merged in a broken state. The diagram makes the constraint explicit without requiring you to read the code. - Two final states: Both
MergedandClosedare terminal states. Every PR ends one of these two ways. Multiple final states are valid and common in business process models.
Example 3: Food Delivery — Order Lifecycle
Scenario: Once placed, an order moves through a sequence of states from the restaurant’s kitchen to the customer’s door. Unlike the PR lifecycle, this flow is mostly linear — the diagram below shows the simplest case where the only cancellation path fires when the restaurant declines a freshly placed order. (A production system would also model customer-initiated cancellation from Confirmed and Preparing; we omit those arrows here to keep the happy path readable, but see the Self-Correction exercise below.)
Detailed description
UML state machine diagram with 7 states (Placed, Confirmed, Cancelled, Preparing, ReadyForPickup, InTransit, Delivered). Transitions: the initial pseudostate transitions to Placed on submitOrder(); Placed transitions to Confirmed on restaurantAccepts(); Placed transitions to Cancelled on restaurantDeclines() / refundPayment(); Confirmed transitions to Preparing on kitchenStart(); Preparing transitions to ReadyForPickup on foodReady(); ReadyForPickup transitions to InTransit on driverPickedUp(); InTransit transitions to Delivered on driverArrived() / notifyCustomer(); Delivered transitions to the final state; Cancelled transitions to the final state.
States
- Placed
- Confirmed
- Cancelled
- Preparing
- ReadyForPickup
- InTransit
- Delivered
Transitions
- the initial pseudostate transitions to Placed on submitOrder()
- Placed transitions to Confirmed on restaurantAccepts()
- Placed transitions to Cancelled on restaurantDeclines() / refundPayment()
- Confirmed transitions to Preparing on kitchenStart()
- Preparing transitions to ReadyForPickup on foodReady()
- ReadyForPickup transitions to InTransit on driverPickedUp()
- InTransit transitions to Delivered on driverArrived() / notifyCustomer()
- Delivered transitions to the final state
- Cancelled transitions to the final state
Reading the diagram:
- Early exit with effect:
Placed → Cancelledfires if the restaurant declines, triggering/ refundPayment(). The effect makes the business rule explicit: every cancellation must trigger a refund. - The happy path is visually obvious:
Placed → Confirmed → Preparing → ReadyForPickup → InTransit → Deliveredflows in a clear left-to-right, top-to-bottom reading. A new engineer on the team can understand the order lifecycle in 30 seconds. - Effect on delivery (
/ notifyCustomer()): The customer gets a push notification the moment the driver marks the order delivered. Transition effects tie business actions to the precise moment a state change occurs. - Two terminal states:
DeliveredandCancelledboth lead to[*]. An order always ends — there is no indefinitely running lifecycle for a delivery order, unlike a server or a music player.
⚠ Common Mistakes in State Machines
| # | Mistake | Fix |
|---|---|---|
| 1 | Conflating event and guard — writing powerLow as a state or as a guard instead of as an event trigger |
An event is something that happens externally (powerLow() was received); a guard is a condition evaluated when the event fires ([battery < 5%]). The label syntax is Event [Guard] / Effect — in that order. |
| 2 | No initial state — forgetting the solid black circle and entry transition | Every state machine must have a clear starting point. Omit it and the diagram is ambiguous about how the object begins its life. |
| 3 | Dangling states — states that cannot be reached or cannot be left | Trace every state: is there a path from the initial transition to it? Is there a way out (or is it a final state)? Both directions must be answered. |
| 4 | Overlapping guards — two transitions on the same event with guards that can be simultaneously true | Guards on the same event must be mutually exclusive (e.g., [x > 0] and [x <= 0]). Otherwise the machine is non-deterministic. |
| 5 | Using a state machine for something that is not stateful — modeling a sequence of steps with no branching based on past events | If the object reacts the same way to the same input regardless of history, it does not need a state machine — use an activity or sequence diagram instead. |
🛠️ Retrieval Practice
To ensure these concepts are transferring from working memory to long-term retention, take a moment to answer these questions without looking back at the text:
- What is the difference between an Event and a Guard on a transition line?
- In our exosuit example, what would happen if
threatDetectedoccurs, but the guard[sysCheckOK]evaluates tofalse? What state does the system remain in? - Challenge: Sketch a simple state machine on a piece of paper for a standard turnstile (which can be either Locked or Unlocked, responding to the events insertCoin and push).
Self-Correction Check: If you struggled with question 2, revisit Section 2.2 to review how Guards act as gatekeepers for transitions.
Practice
Test your knowledge with these retrieval practice exercises.
UML State Machine Diagram Flashcards
Quick review of UML State Machine Diagram notation and transitions.
What is the syntax for a transition label in a state machine diagram?
What do the initial pseudostate and final state look like?
What happens when a transition’s guard condition evaluates to false?
How should states be named according to UML conventions?
When should you use a state machine diagram instead of a sequence diagram?
What are the three types of internal activities a state can have?
Does a state machine always need a final state?
UML State Machine Diagram Practice
Test your ability to read and interpret UML State Machine Diagrams.
What does the solid black circle represent in a state machine diagram?
Detailed description
UML state machine diagram with 2 states (Idle, Active). Transitions: the initial pseudostate transitions to Idle on powerOn(); Idle transitions to Active on start().
States
- Idle
- Active
Transitions
- the initial pseudostate transitions to Idle on powerOn()
- Idle transitions to Active on start()
Given the transition label buttonPressed [isEnabled] / playSound(), which part is the guard condition?
Detailed description
UML state machine diagram with 2 states (Idle, Running). Transitions: the initial pseudostate transitions to Idle; Idle transitions to Running on startButton [isReady] / initDisplay(); Running transitions to Idle on stopButton / saveState().
States
- Idle
- Running
Transitions
- the initial pseudostate transitions to Idle
- Idle transitions to Running on startButton [isReady] / initDisplay()
- Running transitions to Idle on stopButton / saveState()
In this diagram, what happens if threatDetected occurs but sysCheckOK is false?
Detailed description
UML state machine diagram with 2 states (Idle, CombatMode). Transitions: the initial pseudostate transitions to Idle on powerOn(); Idle transitions to CombatMode on threatDetected [sysCheckOK] / deployUI(); CombatMode transitions to Idle on threatNeutralized / retractWeapons().
States
- Idle
- CombatMode
Transitions
- the initial pseudostate transitions to Idle on powerOn()
- Idle transitions to CombatMode on threatDetected [sysCheckOK] / deployUI()
- CombatMode transitions to Idle on threatNeutralized / retractWeapons()
Which of the following are valid components of a UML transition label? (Select all that apply.)
Syntax: Event [Guard] / Effect
What does the symbol ◎ (a filled circle inside a hollow circle) represent?
Detailed description
UML state machine diagram with 1 state (Active). Transitions: the initial pseudostate transitions to Active on create(); Active transitions to the final state on destroy().
States
- Active
Transitions
- the initial pseudostate transitions to Active on create()
- Active transitions to the final state on destroy()
Which of these is a well-named state according to UML conventions?
Detailed description
UML state machine diagram with 3 states (WaitingForInput, Processing, DisplayingResults). Transitions: the initial pseudostate transitions to WaitingForInput; WaitingForInput transitions to Processing on submitForm; Processing transitions to DisplayingResults on dataLoaded; DisplayingResults transitions to WaitingForInput on reset; DisplayingResults transitions to the final state on logout.
States
- WaitingForInput
- Processing
- DisplayingResults
Transitions
- the initial pseudostate transitions to WaitingForInput
- WaitingForInput transitions to Processing on submitForm
- Processing transitions to DisplayingResults on dataLoaded
- DisplayingResults transitions to WaitingForInput on reset
- DisplayingResults transitions to the final state on logout
When should you choose a state machine diagram over a sequence diagram?
Look at this diagram. What is the effect that executes when transitioning from CombatMode to Idle?
Detailed description
UML state machine diagram with 3 states (Idle, CombatMode, EmergencyPower). Transitions: the initial pseudostate transitions to Idle on powerOn(); Idle transitions to CombatMode on threatDetected [sysCheckOK] / deployUI(); CombatMode transitions to Idle on threatNeutralized / retractWeapons(); CombatMode transitions to EmergencyPower on powerCritical / rerouteToLifeSupport(); EmergencyPower transitions to the final state on manualOverride().
States
- Idle
- CombatMode
- EmergencyPower
Transitions
- the initial pseudostate transitions to Idle on powerOn()
- Idle transitions to CombatMode on threatDetected [sysCheckOK] / deployUI()
- CombatMode transitions to Idle on threatNeutralized / retractWeapons()
- CombatMode transitions to EmergencyPower on powerCritical / rerouteToLifeSupport()
- EmergencyPower transitions to the final state on manualOverride()
How many states (not counting the initial pseudostate or final state) are in this diagram?
Detailed description
UML state machine diagram with 5 states (Created, Paid, Shipped, Delivered, Cancelled). Transitions: the initial pseudostate transitions to Created on orderPlaced; Created transitions to Paid on paymentReceived; Paid transitions to Shipped on itemDispatched; Shipped transitions to Delivered on deliveryConfirmed; Created transitions to Cancelled on customerCancels; Delivered transitions to the final state; Cancelled transitions to the final state.
States
- Created
- Paid
- Shipped
- Delivered
- Cancelled
Transitions
- the initial pseudostate transitions to Created on orderPlaced
- Created transitions to Paid on paymentReceived
- Paid transitions to Shipped on itemDispatched
- Shipped transitions to Delivered on deliveryConfirmed
- Created transitions to Cancelled on customerCancels
- Delivered transitions to the final state
- Cancelled transitions to the final state
In this diagram, which transition has both a guard condition and an effect?
Detailed description
UML state machine diagram with 3 states (Idle, CombatMode, EmergencyPower). Transitions: the initial pseudostate transitions to Idle on powerOn(); Idle transitions to CombatMode on threatDetected [sysCheckOK] / deployUI(); CombatMode transitions to Idle on threatNeutralized / retractWeapons(); CombatMode transitions to EmergencyPower on powerCritical / rerouteToLifeSupport().
States
- Idle
- CombatMode
- EmergencyPower
Transitions
- the initial pseudostate transitions to Idle on powerOn()
- Idle transitions to CombatMode on threatDetected [sysCheckOK] / deployUI()
- CombatMode transitions to Idle on threatNeutralized / retractWeapons()
- CombatMode transitions to EmergencyPower on powerCritical / rerouteToLifeSupport()
Which of the following are true about the initial pseudostate () in a state machine diagram? (Select all that apply.)
What is the difference between an entry/ internal activity and an effect on a transition (/ action)?
Detailed description
UML state machine diagram with 3 states (Connecting, Connected, Error). Transitions: the initial pseudostate transitions to Connecting on connect(); Connecting transitions to Connected on handshakeOK / logSuccess(); Connecting transitions to Error on timeout / logError().
States
- Connecting
- Connected
- Error
Transitions
- the initial pseudostate transitions to Connecting on connect()
- Connecting transitions to Connected on handshakeOK / logSuccess()
- Connecting transitions to Error on timeout / logError()
Does every state machine diagram need a final state?
Detailed description
UML state machine diagram with 2 states (Listening, Processing). Transitions: the initial pseudostate transitions to Listening on start(); Listening transitions to Processing on requestReceived; Processing transitions to Listening on requestHandled.
States
- Listening
- Processing
Transitions
- the initial pseudostate transitions to Listening on start()
- Listening transitions to Processing on requestReceived
- Processing transitions to Listening on requestHandled
Pedagogical Tip: If you find these challenging, it’s a good sign! Effortful retrieval is exactly what builds durable mental models. Try coming back to these tomorrow to benefit from spacing and interleaving.