State Pattern Implementation in Java
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
State Pattern in Java: what you actually reach for
Java implementation
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 FreeThe Java-specific trap
Performance in Java, beyond the O(1)
Real-World Applications
Interview Tips & Practice
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).
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 trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
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.