String POOL in java

后端 未结 4 1097
隐瞒了意图╮
隐瞒了意图╮ 2021-01-04 21:06

Java has string pool, due to which objects of string class are immutable.

But my question stands -

What was the need to make String POOL?

4条回答
  •  离开以前
    2021-01-04 22:02

    A pool is possible because the strings are immutable. But the immutability of the String hasn't been decided only because of this pool. Immutability has numerous other benefits. BTW, a Double is also immutable, and there is no pool of Doubles.

    The need for the String pool is to reduce the memory needed to hold all the String literals (and the interned Strings) a program uses, since these literals have a good chance of being used many times, in many places of the program. Instead of having thousands of copies of the same String literal, you just have thousand references to the same String, which reduces the memory usage.

    Note that the String class is not different from other classes: it holds its own char array. It may also share it with other String instances, though, when substring is called.

提交回复
热议问题