Java: Why is constant pool maintained only for String values ?

前端 未结 2 1249
情话喂你
情话喂你 2021-02-05 19:19

My question is about java interning and constant pools.

Java maintains a a constants pool for java.lang.String, to use JVM memory cleverly, and to do so jav

2条回答
  •  無奈伤痛
    2021-02-05 19:32

    Well, because String objects are immutable, it's safe for multiple references to "share" the same String object.

    public class ImmutableStrings
    {
    public static void main(String[] args)
    {
        String one = "str1";
        String two = "str1";
    
        System.out.println(one.equals(two));
        System.out.println(one == two);
    }
    }
    
    // Output
    
    true
    true
    

    In such a case, there is really no need to make two instances of an identical String object. If a String object could be changed, as a StringBuffer can be changed, we would be forced to create two separate objects. But, as we know that String objects cannot change, we can safely share a String object among the two String references, one and two. This is done through the String literal pool.

    You can go through this link to know in details.

提交回复
热议问题