You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

String.intern()文档称字符串池初始为空,该说法是否属实?

Is the "String pool is initially empty" claim in String.intern() Javadoc true?

Great question! The short answer is: No, this isn't strictly accurate in real-world JVM execution, even though the Javadoc uses that wording for conceptual simplicity.

Let's unpack this:

First, let's restate the relevant Javadoc snippet for context:

返回字符串对象的规范表示形式。String类私有维护一个初始为空的字符串池。调用intern方法时,如果池中已存在与该String对象equals(Object)方法判定相等的字符串,则返回池中的字符串;否则,将此String对象添加到池中并返回其引用。后续……

Here's why the "initially empty" part doesn't hold up in practice:

  • The string pool (a subset of the JVM's runtime constant pool) gets populated with system-level strings during JVM startup. Before any user code runs, core Java classes (like java.lang.String, java.lang.Object) are loaded, and their associated string constants (e.g., "java", "lang", "String") are already stored in the pool.
  • The Javadoc's wording is likely simplifying the idea to focus on user-controlled strings—meaning no strings added by your code are present initially. But technically, the pool isn't truly empty from the moment the JVM boots.

You can verify this with a quick test:

public class PoolTest {
    public static void main(String[] args) {
        String testStr = "java";
        // If "java" was already in the pool, intern() returns the same reference
        System.out.println(testStr == testStr.intern()); // Outputs true
    }
}

This prints true because "java" was already loaded into the pool when the JVM initialized the java.lang package—long before our main method ran.

So to sum up: The Javadoc's description is a simplified abstraction, but in actual JVM operation, the string pool isn't empty at startup.

内容的提问来源于stack exchange,提问作者Udayan Khattry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:22:35