You can specify the string to be added to the literal pool (called interning in Java) by calling String.intern() as follows:
final String bar = myString.intern();
This is basically the same concept as a literal pool, using the same object for a given string. Note that string literals are interned automatically. It also allows you to compare interned strings by reference, so it can be more efficient. However, you should always compare strings returned with intern() . Thus,
a.equals(b);
can be replaced by
a.intern() == b.intern();
Note that you really do not want this to be exactly as shown. Ideally, you can keep interned strings around and reuse them. However, there are some pitfalls for interned strings. They are not going to garbage, and the method itself is a little expensive.
Zong
source share