Can we say that, Java String implements the Flyweight design pattern?
Not really. Or at best you can say that it can implement that pattern.
The string constant pool only contains String
objects that correspond to:
- Java string >>literals<< in the source code,
- other compile-time string constants, and
- String objects that have been deliberately "interned" by an application or library method calling the
String.intern()
method.
Normal Java String
objects are not created in the string pool. Instead, they are created in the normal heap, and only "put into the pool" by a call to intern()
. This is for good reason. If all strings were interned by default, it would increase GC overheads and/or the long-term memory footprint of a typical Java application.
(Note that Java 8 now has an optional string deduplication feature in the G1 collector which saves space by combining the char arrays of strings that are equal.)