StringBuilder / StringBuffer with literal string in memory [duplicate]

  • A+
Category:Languages

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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: