Below is a compact, yet reasonably accurate, “typestate” model of java.lang.StringBuilder rendered in GraphViz dot syntax.
The model focuses on the observable protocol (i.e., how client code is allowed to interact with a StringBuilder) rather than on every internal bit (capacity, index values, etc.).
Three abstraction levels are distinguished:
• Initial ‑ the builder has just been constructed and no mutating call has happened.
• Mutated ‑ at least one mutating call (append, insert, delete, replace, reverse, setCharAt, ensureCapacity, …) has occurred.
• ToStringCalled ‑ at least one toString() has been performed. (A builder can still be mutated after this; we just remember that a materialized String has been requested.)
Read-only queries (length, capacity, charAt, substring, indexOf, etc.) are modeled as self-loops because they do not change the abstract state.
Any mutating method moves the object to (or keeps it in) Mutated.
toString() is always legal and moves to ToStringCalled.
• Calling toString() repeatedly is fine (self-loop).
• Mutating after toString() is also fine (edge back to Mutated).
Queries (length, capacity, etc.) never change the abstract state (self-loops).
Why this abstraction?
• StringBuilder has no true “closed” or “invalid” state; you can always keep using it.
• Distinguishing whether toString() has happened can be useful for analyses that reason about defensive copying, sharing, or performance.
• Finer details (e.g., capacity management, index bounds) are intentionally abstracted away; those belong to data-flow analysis rather than typestate.
Feel free to tweak the states or labels depending on the granularity you need!