Yes, Strings can be garbage collected in Java. The eligibility for garbage collection of Strings in Java completely depends on how they were created.
If Strings are created dynamically at runtime such as using the new keyword , concatenating non-constant strings or reading data from a file , those strings occupy memory in heap memory .As soon as these types of strings become unreachable i.e. no active thread or variable holds a reference to them , they become eligible for garbage collection .
Secondly if the Strings are created as hardcoded literals (e.g. String s=”Gift” ) or dynamically added using the intern() method are placed inside the String Constant Pool . Now let’s check how the strings present in String Constant Pool are garbage collected.
If you add manually a dynamic string to the pool using String.intern() , it can be garbage collected as soon as it becomes unreachable by your application i.e. when no active references remain.
A hardcoded string literal can only be garbage collected if the defining class that contains the literal is unloaded by its ClassLoader .
