Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String POOL in java

Tags:

java

string

pool

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?

Why string class was not kept like other class to hold its own values?

Is internally JVM need some strings or is this a performance benefit. If yes how?

like image 379
Amol Ghotankar Avatar asked Jan 09 '12 12:01

Amol Ghotankar


1 Answers

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.

like image 164
JB Nizet Avatar answered Oct 03 '22 14:10

JB Nizet