Java Fundamentals

UML Behavioral Diagrams

Use Case, Activity, and Sequence Diagrams

Recap: UML Class Diagrams

In Lecture 1, we learned about structural diagrams:

Today: We'll learn behavioral diagrams that show how a system works dynamically!

UML Diagram Categories

Structural Diagrams Behavioral Diagrams
Class Diagram Use Case Diagram
Object Diagram Activity Diagram
Component Diagram Sequence Diagram
Package Diagram State Machine Diagram
Deployment Diagram Communication Diagram

Today we focus on the three most common behavioral diagrams (in bold)

Part 1: Use Case Diagrams

A use case diagram shows what a system does from a user's perspective.

Key Question: "What can users do with this system?"

Use Case Diagram Components

Element Symbol Description
Actor Stick figure Someone or something that interacts with the system
Use Case Oval/Ellipse A specific functionality or action the system provides
System Boundary Rectangle Defines the scope of the system
Association Solid line Connects actors to use cases they can perform

Use Case Diagram Example: Online Shopping

flowchart LR
    subgraph System["Online Shop System"]
        UC1(["Browse Products"])
        UC2(["Add to Cart"])
        UC3(["Checkout"])
        UC4(["Make Payment"])
        UC3 -.->|include| UC4
    end

    Customer[/Customer\]
    Customer --- UC1
    Customer --- UC2
    Customer --- UC3
    Customer --- UC4
        

Use Case Relationships

Relationship Notation Meaning
Include «include» → Use case A always includes use case B
Extend «extend» → Use case B optionally extends use case A
Generalization ──▷ One actor/use case inherits from another
Include: "Checkout" always includes "Make Payment"
Extend: "Apply Coupon" optionally extends "Checkout"

Types of Actors

Exercise 1: Library Management Use Cases

Create a use case diagram for a Library Management System with these requirements:

Hints:
  • Use generalization between Member and Librarian
  • "Borrow book" should «include» "Check availability"
  • "Return book" could «extend» with "Pay fine"

Part 2: Activity Diagrams

An activity diagram shows the flow of activities in a process.

Key Question: "What steps happen, and in what order?"

Activity Diagram Components

Element Symbol Description
Initial Node ● (filled circle) Starting point of the flow
Final Node ⊙ (circle with border) End point of the flow
Activity Rounded rectangle An action or task to perform
Decision ◇ (diamond) Branch based on condition
Merge ◇ (diamond) Joins multiple paths into one
Fork Thick horizontal bar Splits into parallel activities
Join Thick horizontal bar Waits for all parallel activities

Activity Diagram Example: Order Processing

flowchart TD
    Start((●)) --> ReceiveOrder["Receive Order"]
    ReceiveOrder --> CheckStock{In Stock?}
    CheckStock -->|No| CancelOrder["Cancel Order"]
    CancelOrder --> End1((⊙))
    CheckStock -->|Yes| Fork[/ /]
    Fork --> PackItems["Pack Items"]
    Fork --> ProcessPayment["Process Payment"]
    PackItems --> Join[\ \]
    ProcessPayment --> Join
    Join --> ShipOrder["Ship Order"]
    ShipOrder --> End2((⊙))
        

Activity Diagrams with Swimlanes

Swimlanes partition activities by responsibility (actor, department, system).

flowchart TD
    subgraph Customer
        A((●)) --> B["Place Order"]
        G["Receive Order"] --> H((⊙))
    end
    subgraph System
        C["Verify Stock"]
        F["Send Notification"]
    end
    subgraph Warehouse
        D["Pack Order"]
        E["Ship Order"]
    end

    B --> C
    C --> D
    D --> E
    E --> F
    F --> G
        

Decision and Guard Conditions

Use guard conditions in brackets to control flow:

flowchart TD
    CheckLogin["Check Login"] --> Decision{Valid?}
    Decision -->|"[invalid]"| ShowError["Show Error"]
    Decision -->|"[valid]"| ShowDashboard["Show Dashboard"]
    ShowError --> Merge{" "}
    ShowDashboard --> Merge
    Merge --> LogEvent["Log Event"]
        

Exercise 2: ATM Withdrawal Activity Diagram

Create an activity diagram for an ATM cash withdrawal process:

  1. User inserts card
  2. System validates card
  3. If invalid → show error → eject card → end
  4. If valid → ask for PIN
  5. If PIN wrong (max 3 attempts) → block card → end
  6. If PIN correct → show menu → select withdrawal
  7. Enter amount
  8. Check balance: if insufficient → show error → back to menu
  9. If sufficient → dispense cash AND print receipt (parallel)
  10. Eject card → end
Use: Decision nodes, fork/join for parallel operations, guard conditions

Part 3: Sequence Diagrams

A sequence diagram shows how objects interact over time.

Key Question: "What messages are sent between objects, and in what order?"

Sequence Diagram Components

Element Description
Lifeline Vertical dashed line representing an object's existence over time
Activation Box Rectangle on lifeline showing when object is active/processing
Synchronous Message Solid arrow with filled head (→) - sender waits for response
Return Message Dashed arrow (- - →) - response to synchronous message
Asynchronous Message Solid arrow with open head (→) - sender doesn't wait
Self-call Arrow that loops back to the same lifeline

Sequence Diagram Example: User Login

sequenceDiagram
    actor User
    participant LoginForm
    participant AuthService
    participant Database

    User->>LoginForm: enter credentials
    LoginForm->>AuthService: validate()
    AuthService->>Database: findUser()
    Database-->>AuthService: user data
    AuthService->>AuthService: checkPassword
    AuthService-->>LoginForm: auth result
    LoginForm-->>User: show result
        

Combined Fragments

Fragments add control flow logic to sequence diagrams:

Fragment Meaning Use Case
alt Alternative (if-else) Different paths based on condition
opt Optional (if) Executes only if condition is true
loop Loop Repeats messages while condition holds
par Parallel Concurrent execution
ref Reference References another sequence diagram

Example: Alt Fragment (If-Else)

sequenceDiagram
    participant Client
    participant Server
    participant Database

    Client->>Server: request()
    Server->>Database: query()

    alt data found
        Database-->>Server: data
        Server-->>Client: success
    else data not found
        Database-->>Server: null
        Server-->>Client: error 404
    end
        

Example: Loop Fragment

sequenceDiagram
    participant ShoppingCart
    participant ProductService
    participant Inventory

    loop for each item in cart
        ShoppingCart->>ProductService: getPrice(item)
        ProductService->>Inventory: checkStock()
        Inventory-->>ProductService: quantity
        ProductService-->>ShoppingCart: price + stock
    end

    ShoppingCart->>ShoppingCart: calculateTotal
        

Object Creation and Destruction

sequenceDiagram
    participant OrderService
    participant Order
    participant EmailService

    OrderService->>Order: create new Order()
    activate Order
    OrderService->>Order: addItem(product)
    OrderService->>Order: confirm()
    Order->>EmailService: sendConfirmation()
    EmailService-->>Order: done
    OrderService->>Order: destroy
    deactivate Order
    destroy Order
        

create: Creates new object | destroy: Object destruction

Sequence Diagram Best Practices

Exercise 3: Online Purchase Sequence Diagram

Create a sequence diagram for an online purchase with these objects:

Scenario:

  1. Customer clicks "Checkout" on WebUI
  2. WebUI gets cart total from CartService
  3. CartService checks each item's availability with InventoryService (loop)
  4. WebUI sends payment to PaymentGateway
  5. Use alt fragment: if payment succeeds → reserve items, send confirmation email; if fails → show error

When to Use Which Diagram?

Diagram Best For Key Question
Use Case Requirements gathering, stakeholder communication What can users do?
Activity Business processes, algorithms, workflows What steps happen?
Sequence Object interactions, API design, debugging How do objects talk?
Class System structure, database design What entities exist?
In practice: Use case → Activity → Class → Sequence (from requirements to implementation)

UML Diagramming Tools

Recommendation: Start with Mermaid for quick diagrams (used in this course!) or draw.io for visual editing

Exercise 4: Complete System Analysis

Design a Hotel Reservation System using all three diagram types:

  1. Use Case Diagram:
    • Actors: Guest, Receptionist, System
    • Use cases: Search rooms, Make reservation, Cancel reservation, Check-in, Check-out, Process payment, Send confirmation
  2. Activity Diagram:
    • Model the complete reservation process from search to confirmation
    • Include decisions (room available?), parallel activities (payment + email)
  3. Sequence Diagram:
    • Detail the "Make reservation" use case
    • Show interactions between Guest, WebUI, RoomService, PaymentService, EmailService

Summary

Diagram Shows Key Elements
Use Case System functionality Actors, use cases, include/extend
Activity Process flow Activities, decisions, fork/join, swimlanes
Sequence Object interactions Lifelines, messages, fragments (alt/loop/opt)
Next lecture: We'll start coding in Java! Setting up your IDE and writing your first program.

Slide Overview