The JVM caches Integer objects from -128 to 127 and reuses string literals from the string pool. Which pattern is this?
Options
- Flyweight: share common immutable objects instead of making copies (Correct option)
- Observer: objects get notified when another object changes state
- Command: each request is wrapped inside its own object
- Mediator: objects talk to each other through a central object
Answer
Flyweight: share common immutable objects instead of creating many identical ones
Why
Flyweight saves memory by sharing objects that are identical and immutable instead of creating duplicates.
Integer.valueOf(100) always returns the same cached object; identical string literals share one String in the pool.
It only works safely when the shared object is immutable.
Remember
Flyweight = share identical immutable objects.