"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Are String Literals Ever Garbage Collected in Java?

Are String Literals Ever Garbage Collected in Java?

Published on 2024-11-08
Browse:492

 Are String Literals Ever Garbage Collected in Java?

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3