Garbage Collection of String Literals
Q1: If a string is defined as a literal at compile time (e.g., String str = "java"), will it be garbage collected?
Not typically. Code objects contain references to literal String objects, keeping them reachable. Garbage collection only occurs when code objects become unreachable.
Q2: If the intern method is used (e.g., String str = new String("java").intern()), will it be garbage collected?
The returned object will be the same as the "java" string literal, which is interned at class loading time. Therefore, it will not be garbage collected. However, interned strings that are not identical to string literals can be garbage collected when they become unreachable.
Q3: Does it make sense that literals will be garbage collected only when the String class is unloaded?
No. The String class is essential for the Java Virtual Machine and is unlikely to be unloaded. Sources stating otherwise are incorrect.
The above is the detailed content of Are String Literals Ever Garbage Collected in Java?. For more information, please follow other related articles on the PHP Chinese website!