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?
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.
A string literal always refers to the same instance of class
String
. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the methodString.intern
.JLS 11 > 3. Lexical Structure > 3.10.5. String Literals
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With