Video in progress
What is the String pool, and what's the difference between "abc" and new String("abc")?
The String pool is a special table on the heap where literal strings are kept as a single copy. "abc" gets the object from the pool, while new String("abc") always creates a new object. intern() replaces a string with the copy in the pool.
📖 Answer
String a = "abc";
String b = "abc";
String c = new String("abc");
a == b; // true: both are one object in the pool
a == c; // false: c is a new object
a == c.intern(); // true
Compile-time constants are merged too:
String d = "ab" + "c"; // the compiler makes it "abc" -> pool
String part = "ab";
String e = part + "c"; // computed at runtime -> a new object
a == d; // true
a == e; // false
What follows from this in practice:
- you almost never need
new String("..."); - always compare strings with
equals: the result of==depends on how the code is written and can't be trusted; - since Java 7 the pool lives on the regular heap, so the GC can clean it up;
- you can use
intern()to save memory for heavily repeated values, but G1's-XX:+UseStringDeduplicationoption does that automatically and more safely.
Sign up to mark studied questions and save your progress.