Skip to contentSaltar al contenido
125+ QA and SEO checks per page

State Pattern Implementation in Java

14 min readintermediate
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓State Pattern runs in O(1) time and O(n) space, in Java as in every other language.
  • ✓Java has a construct built for this pattern: an enum whose constants each supply their own implementation of an abstract method, so the state and its behaviour are declared together and the compiler requires every constant to implement it.
  • ✓Use the constant-specific method enum when states share a shape and carry no per-state data, because it is compact and the compiler enforces completeness by construction.
  • ✓The Java trap: A switch over an enum without a default compiles even when a constant is unhandled, and merely returns nothing or falls through, so the classic enum switch has no exhaustiveness guarantee at all; only the arrow-form switch EXPRESSION over an enum requires exhaustiveness, and only a sealed hierarchy gets it for classes.
  • ✓Enum switch compiles to a tableswitch on the ordinal, so it is a constant-time jump with no hashing.

What State Pattern actually is

The State pattern lets an object change its behaviour when its internal state changes, by delegating to a per-state object rather than branching on a flag. Written out as classes it is unremarkable; what makes it worth eight separate pages is that this is the pattern where type systems differ most sharply. The real question is not how to represent a state but whether the compiler will tell you when you forget to handle one, and whether it can stop an illegal transition from being written at all. Three languages here prove exhaustiveness at compile time and turn a forgotten state into a build failure. One goes further and can make an invalid transition fail to compile by encoding the state in the type itself. One has an enum construct built specifically for this pattern. And two cannot check any of it, so the discipline has to live in tests.

State Pattern in Java: what you actually reach for

Java has a construct built for this pattern: an enum whose constants each supply their own implementation of an abstract method, so the state and its behaviour are declared together and the compiler requires every constant to implement it. EnumMap and EnumSet are array-backed collections keyed by that enum. Since Java 17, a sealed interface with records gives the alternative when states carry different data, and Java 21 pattern matching for switch checks that hierarchy exhaustively without a default.

Java implementation

Use the constant-specific method enum when states share a shape and carry no per-state data, because it is compact and the compiler enforces completeness by construction. Switch to a sealed interface of records when the states hold different fields, so a reviewer state can carry the reviewer and a published state the timestamp. Use EnumMap rather than HashMap for transition tables keyed by an enum.
java
import java.util.*;

// Constant-specific methods: the compiler REQUIRES every constant to implement next().
enum State {
    DRAFT     { State on(Event e) { return e == Event.SUBMIT ? REVIEW : illegal(e); } },
    REVIEW    { State on(Event e) {
                  return switch (e) {
                      case APPROVE -> PUBLISHED;
                      case REJECT  -> DRAFT;
                      default      -> illegal(e);
                  };
               } },
    PUBLISHED { State on(Event e) { return illegal(e); } };

    abstract State on(Event e);

    State illegal(Event e) {
        throw new IllegalStateException(this + " cannot handle " + e);
    }
}

enum Event { SUBMIT, APPROVE, REJECT }

class Post {
    private State state = State.DRAFT;      // never mutable state ON the constant
    void send(Event e) { state = state.on(e); }
    State state() { return state; }
}

class Demo {
    // EnumMap is array-backed by ordinal: far faster than HashMap here.
    static final Map<State, String> LABELS = new EnumMap<>(Map.of(
        State.DRAFT, "Draft", State.REVIEW, "In review", State.PUBLISHED, "Live"));
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Java-specific trap

A switch over an enum without a default compiles even when a constant is unhandled, and merely returns nothing or falls through, so the classic enum switch has no exhaustiveness guarantee at all; only the arrow-form switch EXPRESSION over an enum requires exhaustiveness, and only a sealed hierarchy gets it for classes. Separately, enum constants are singletons per class loader, so putting mutable state on a constant makes it shared across the entire application, which is the usual source of a state machine that mysteriously affects unrelated requests.

Performance in Java, beyond the O(1)

Enum switch compiles to a tableswitch on the ordinal, so it is a constant-time jump with no hashing. EnumMap is backed by a plain array indexed by ordinal, so lookups are array accesses and it is substantially faster and smaller than a HashMap. The constant-specific method form dispatches virtually, and since each constant is its own anonymous subclass the call site is megamorphic once there are more than two states, which blocks inlining; for a very hot machine a switch expression is faster. The asymptotic cost is the same in every language, O(1) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port State Pattern between languages.

Real-World Applications

State Pattern is used extensively in production software: framework internals, plugin architectures, state management libraries, and large-scale application architectures all rely on this pattern. In Java, check whether the standard library or a well maintained package already provides it before you write your own. Understanding State Pattern helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

State Pattern appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose State Pattern over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of State Pattern to build pattern recognition. In Java, demonstrate proficiency with generics and streams API to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Java code that is both correct and maintainable.

Frequently Asked Questions

Which Java type or library should I use for State Pattern?

Java has a construct built for this pattern: an enum whose constants each supply their own implementation of an abstract method, so the state and its behaviour are declared together and the compiler requires every constant to implement it. EnumMap and EnumSet are array-backed collections keyed by that enum. Since Java 17, a sealed interface with records gives the alternative when states carry different data, and Java 21 pattern matching for switch checks that hierarchy exhaustively without a default.

What is the most common Java mistake when implementing State Pattern?

A switch over an enum without a default compiles even when a constant is unhandled, and merely returns nothing or falls through, so the classic enum switch has no exhaustiveness guarantee at all; only the arrow-form switch EXPRESSION over an enum requires exhaustiveness, and only a sealed hierarchy gets it for classes. Separately, enum constants are singletons per class loader, so putting mutable state on a constant makes it shared across the entire application, which is the usual source of a state machine that mysteriously affects unrelated requests.

How does State Pattern actually perform in Java?

Enum switch compiles to a tableswitch on the ordinal, so it is a constant-time jump with no hashing. EnumMap is backed by a plain array indexed by ordinal, so lookups are array accesses and it is substantially faster and smaller than a HashMap. The constant-specific method form dispatches virtually, and since each constant is its own anonymous subclass the call site is megamorphic once there are more than two states, which blocks inlining; for a very hot machine a switch expression is faster. Time complexity is O(1) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

If you are a student, see what Replit offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.