java - Reclaim first reference of Immutable String -


i see many q&a immutable string saying jvm create new reference when following:

string text = "apple"; text = "orange"; // new reference created 

my question is, happen previous reference "apple"? since java garbage collection automatic, means there no intentional way re-claim memory?

edit: reason asking question know how should handle string variables in future.

does string literals cleared gc? if not, wouldn't pool going huge until point goes out of memory? considering if program receives different string values textbox on ui, each different values user enters going add on pool.

there no way intentionally reclaim memory system.gc() (which suggestion jvm).

even when garbage collection runs, "apple" won't reclaimed.

according jls 3.10.5, string literals interned in string pool and never garbage collected.

quoting:

a string literal reference instance of class string (§4.3.1, §4.3.3).

moreover, string literal refers same instance of class string.

this because string literals - or, more generally, strings values of constant expressions (§15.28) - "interned" share unique instances, using method string.intern.

edit

according this answer, interned strings can garbage collected.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -