Is there are way to access the contents of the String constant pool within our own program?
Say I have some basic code that does this:
String str1 = "foo";
String str2 = "bar";
There are now 2 strings floating around in our String constant pool. Is there some way to access the pool and print out the above values or get the current total number of elements currently contained in the pool?
i.e.
StringConstantPool pool = new StringConstantPool();
System.out.println(pool.getSize()); // etc
All Strings are stored in the String Pool (or String Intern Pool) that is allocated in the Java heap. String pool is an implementation of the String Interring Concept. String Interning is a method that stores only a copy of each distinct string literal. The distinct values are stored in the String pool.
The method intern() creates an exact copy of a String object in the heap memory and stores it in the String constant pool. Note that, if another String with the same contents exists in the String constant pool, then a new object won't be created and the new reference will point to the other String.
The String constant pool is a special memory area. When we declare a String literal, the JVM creates the object in the pool and stores its reference on the stack. Before creating each String object in memory, the JVM performs some steps to decrease the memory overhead.
From Java 7 onwards, the Java String Pool is stored in the Heap space, which is garbage collected by the JVM.
You cannot directly access the String intern pool
.
As per Javadocs String intern pool
is:
A pool of strings, initially empty, is maintained privately by the class String.
However String objects can be added to this pool using String's intern()
method.
java.lang.String.intern()
returns an interned String, that is, one that has an entry in the global String pool. If the String is not already in the global String pool, then it will be added.
Programmatically you can follow this approach:
Set<String> StringConstantPool = new HashSet<String>();
String.intern()
String
value into this pool StringConstantPool
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With