A state machine diagram, simply known as a state diagram, is a type of Unified Modeling Language (UML) diagram. It comes under the category of behavioral diagrams, as it models the behavior of system components as state transitions. State diagrams represent a class's condition at a given instance of time and how it transitions to other conditions under certain circumstances.
Note: Not every class has to be modeled using a state diagram. We only need to represent the state transitions of dynamic classes with temporal importance.
A state diagram comprises various essential components, which are as follows:
States
Initial and final states
Transitions
State actions
Fork and join
A state is the condition of the class at a given time. It is represented by a rectangle with rounded edges. The name of the state is written inside the rectangle in upper camelcase.
The initial state represents the condition the class is in when it is created. It is depicted as a black circle.
The final state represents the condition of the class at the end of the execution flow. It is depicted as a black circle with a ring around it.
The transition of the class from one state to another is represented by arrows. These arrows are labeled, with each label having the following components:
Events: An event is a trigger that causes the change of state.
Guards: Guards mention the conditions that must be true for the transition to occur. When the event occurs, the guard condition is first checked. If it is true, the class changes its state accordingly. Guard conditions are written in square brackets.
Activities: Activities represent the effects invoked on the object in question when the state change occurs. These are separated from the event with a '/' and written in italics.
Note: The activities and guard conditions are optional.
Sometimes, the same activities are invoked every time in the same transition. For example, an object might be affected similarly whenever some state is entered. Such activities are better associated with the state instead of the transition. These are known as state actions. We write these events and activities inside the state rectangle, as shown below.
A state can often split into several concurrent states. This is represented by forks of the states using a solid rectangular bar. The simultaneous states then join together and transition to a common state, which is drawn in the same way.
Let's understand the components of a state diagram using an example of an alarm clock. We can say that the alarm clock starts with an idle state that displays the current time. A person can manipulate the alarm clock to set the alarm. When the alarm time is reached, the clock goes into a ringing state. This scenario is modeled in the state diagram below.