Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object pool for Java wrappers and String

Tags:

People also ask

Is there a wrapper class for string?

No. String is not a wrapper class, simply because there is no parallel primitive type that it wraps.

What is the string pool in Java?

String pool is nothing but a storage area in Java heap where string literals stores. It is also known as String Intern Pool or String Constant Pool. It is just like object allocation. By default, it is empty and privately maintained by the Java String class.

What is the difference between string pool and heap?

The Java string constant pool is an area in heap memory where Java stores literal string values. The heap is an area of memory used for run-time operations.

Is string pool part of heap?

As the name suggests, String Pool in java is a pool of Strings stored in Java Heap Memory. We know that String is a special class in java and we can create String objects using a new operator as well as providing values in double-quotes.


As you all very well know sometimes Java uses object pools for wrappers and String types, sometimes it doesn't.

For example:

Integer i1 = 1;
Integer i2 = 1;
Integer i3 = new Integer(1);
String s1 = "String";
String s2 = "String";
String s3 = new String ("String");
System.out.println("(i1 == i2) " + (i1 == i2));
System.out.println("(i2 == i3) " + (i2 == i3));
System.out.println("(s1 == s2) " + (s1 == s2));
System.out.println("(s2 == s3) " + (s2 == s3));

Execution result:

(i1 == i2) true
(i2 == i3) false
(s1 == s2) true
(s2 == s3) false

As you see boxing of primitives takes objects from the pool, creating of a Strings via string literal takes objects from the pool, too. Such objects are actually the same object (operator == returns true on them).

Other mechanisms of creating wrappers and Strings don't take objects from the pool. Objects created these ways are actually different objects (operator == returns false on them).

What confuses me is the fact that the pool is used partially.

If its a memory issue, why not use the pool all of the times? If its not a memory issue - why use it at all?

The question is - what are the reasons for implementing such behavior (= partial usage of the pool)?

The question is rather theoretical, but it has practical application - it can help understand how correctly use custom objects pools and of course understanding how Java works is always good.