StringBuilder / StringBuffer with literal string in memory

Viewed 552

example code:

StringBuffer sb = new StringBuffer("hi");
sb = null;

Question:

will the literal string "hi" somehow stay in memory, even after the StringBuffer has been garbage collected? Or is it just used to create a char array for the StringBuffer and then never put anywhere in memory?

2 Answers

Yes, hi is a compile time constant so it gets interned by the compiler and resides in the string pool.

Moreover G1GC can perform String deduplication as part of JEP 192: String Deduplication in G1 in which case even if hi wasn't interned by javac it might be retained as part of the deduplication.

Related