Quick revision
The short answer
The flyweight pattern saves memory by sharing one object among many uses instead of creating a new one each time. The shared object keeps only intrinsic state, the part that is the same for every use, while extrinsic state, the part that differs per use, is passed in or stored by the caller. The JDK uses it in Integer.valueOf and Boolean.valueOf, in enum constants and in interned String literals, and flyweight objects must be immutable, because a change made by one user would be seen by all of them.
What to remember
In this answer, we saw that a flyweight shares one object among many uses, keeping intrinsic state inside the shared object and passing extrinsic state in from the caller. The JDK applies it in Integer.valueOf and the other wrapper caches, in Boolean.TRUE and FALSE, in interned string literals and in enum constants, which is also why == on boxed numbers above 127 surprises people. Above all, flyweights must be immutable, because a shared object that can change would leak one user's change to everyone.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The flyweight pattern saves memory by sharing one object among many uses instead of creating a new one each time. The shared object keeps only intrinsic state, the part that is the same for every use, while extrinsic state, the part that differs per use, is passed in or stored by the caller. The JDK uses it in Integer.valueOf and Boolean.valueOf, in enum constants and in interned String literals, and flyweight objects must be immutable, because a change made by one user would be seen by all of them.
Why this question is asked
Most Java programs create millions of small objects, and many of them hold exactly the same values. If a million orders each carry their own Boolean TRUE or their own copy of the string EUR, we pay for a million objects that say the same thing. Interviewers ask about flyweight because it connects a textbook pattern to behaviour we meet every day, such as the famous Integer comparison puzzle, and because the immutability rule is a good test of whether we understand shared state. In this answer, we will recap the idea of intrinsic and extrinsic state, look at the JDK flyweights one by one, see the bug that comparing them with == causes, and explain why immutability is the property that makes sharing safe.
1A Quick Recap of Flyweight
Flyweight is a structural pattern whose only goal is to reduce the number of objects. Instead of creating a new object every time we need a value, we ask a factory, and the factory returns an existing instance when one with the same value is already there. Many parts of the program then hold references to the same object.
To make that possible, the pattern divides an object's data in two. Intrinsic state is the part that is identical for every use and can live inside the shared object, such as the glyph shape of the letter A in a text editor. Extrinsic state is the part that changes from use to use, such as where on the page this particular A is drawn. Extrinsic state is not stored in the flyweight; the caller keeps it and passes it in when needed. That split is what lets one object serve thousands of uses.
2Flyweights in the JDK
The best-known JDK flyweight is the Integer cache. Integer.valueOf(int) returns a cached instance for values from -128 to 127, and autoboxing calls valueOf. Short, Byte, Character (for 0 to 127) and Long do the same for small values. Boolean.valueOf always returns one of two constants, Boolean.TRUE or Boolean.FALSE, so there is never a reason to call new Boolean, whose constructor is deprecated for removal along with the other wrapper constructors.
| Factory or construct | What is shared | Range |
|---|---|---|
Integer.valueOf, autoboxing | Integer instances | -128 to 127 (upper bound tunable) |
Long, Short, Byte valueOf | Wrapper instances | -128 to 127 |
Character.valueOf | Character instances | 0 to 127 |
Boolean.valueOf | Boolean.TRUE and Boolean.FALSE | Both values |
String literals, intern() | One String per distinct text | All literals; runtime strings on request |
| Enum constants | One instance per constant | All constants |
Notice the trap in the first lines. Because small values are shared, == seems to work in tests that use small numbers, and then fails in production when an id reaches 128. The cache is an optimisation, not a promise we may rely on for identity, so comparisons must use equals(). The upper limit of the Integer cache can even be raised with a JVM option, which is another reason not to depend on it.
String literals are the other everyday flyweight. The compiler puts every literal into the class file's constant pool, and the JVM interns it: it keeps one String object per distinct literal in a JVM-wide table, so every occurrence of EUR in the code refers to the same object. String.intern() lets us add strings created at runtime to that table. Enum constants are flyweights by design: there is exactly one instance of OrderStatus.PAID in the JVM, which is why == is correct for enums.
3Why Flyweights Must Be Immutable
Sharing is safe only if nobody can change the shared object. Imagine the Integer cache held mutable objects. If one piece of code could set the cached 7 to 8, every other piece of code in the JVM that boxed a 7 would suddenly see 8. The pattern would turn a memory saving into a bug that appears in unrelated code. That is why every JDK flyweight is immutable: Integer, Boolean, String and enum constants have no setters, and their fields are final.
When we write our own flyweights, the same rule applies. A record with final fields of immutable types is a natural fit. If the object holds a list, the list must be unmodifiable too, otherwise a caller can change it through a getter. Immutability also gives us thread safety for free: a shared object that never changes can be read by any number of threads without locks.
java.util.Currency is itself a flyweight: Currency.getInstance returns the same object for the same code. Our wrapper only shows the shape of a factory with a cache, which is the core of every flyweight.
4When Flyweight Is Worth It
The pattern pays off when there are very many objects and few distinct values, for example millions of trades that share a few hundred currency and exchange codes. It does not help when values are mostly unique, because the cache then grows as large as the data and adds a lookup on top. A cache that never evicts can also become a memory leak if the set of values is unbounded, such as user-entered text. So we measure first, with a heap histogram, and share only where duplicates really dominate.
5Follow-up questions
Why does Integer a = 1000, b = 1000; a == b print false?
Autoboxing calls Integer.valueOf, which only caches values from -128 to 127 by default. 1000 is outside the cache, so each assignment creates a new Integer object, and == compares references. The values are equal, so a.equals(b) is true. The rule is to use equals() for wrapper types and keep == for primitives and enums.
Is flyweight the same as a cache or an object pool?
A flyweight factory uses a cache, but the objects in it are shared at the same time by many users and never handed back. An object pool, such as a connection pool, lends a mutable object to one user at a time and expects it back. Pooled objects can be mutable because only one user holds each at a time; flyweights cannot.
Does interning every string save memory?
Only when there are many duplicates. Interning puts strings in a JVM-wide table, so interning unique values only adds overhead and makes them live longer. For a known small set of values, an enum or a private map from value to instance usually gives more control.
6Conclusion
In this answer, we saw that a flyweight shares one object among many uses, keeping intrinsic state inside the shared object and passing extrinsic state in from the caller. The JDK applies it in Integer.valueOf and the other wrapper caches, in Boolean.TRUE and FALSE, in interned string literals and in enum constants, which is also why == on boxed numbers above 127 surprises people. Above all, flyweights must be immutable, because a shared object that can change would leak one user's change to everyone.
Open with
Flyweight is a pattern for saving memory by sharing objects. Instead of creating a new object each time, we ask a factory, and it returns an existing instance if one with the same value already exists.
Then, if they want more
To make that work we split the state: intrinsic state is the same for every use and lives in the shared object, and extrinsic state, the part that differs per use, stays with the caller and is passed in. The JDK has several examples.
Integer.valueOf, which autoboxing uses, caches the values from minus 128 to 127, and Long, Short, Byte and Character do something similar. Boolean.valueOf only ever returns Boolean.TRUE or Boolean.FALSE. String literals are interned, so every EUR literal in the code is the same object, and intern lets us share runtime strings too.
Enum constants are flyweights by design, with exactly one instance each. A side effect people meet is that comparing boxed Integers with == works for 127 and fails for 128, so we always compare wrappers with equals. The property flyweights must have is immutability.
If a shared object could change, one user's change would appear everywhere it is shared, so the Integer cache only works because Integer cannot be modified. Immutability also makes them safe to share across threads without locking. I would only build my own flyweights where a heap histogram shows many duplicate values.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Explain the flyweight pattern and give JDK examples. What property must flyweight...": https://scrivio-interview-library.netlify.app/java/structural-patterns/19488c6397/