Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we access or query the Java String intern (constant) pool?

Tags:

java

string

pool

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
like image 600
CODEBLACK Avatar asked Sep 27 '13 11:09

CODEBLACK


People also ask

What is string pool and what is the use of intern () function?

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.

What is intern () in string?

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.

What is the use of string constant pool in Java?

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.

Is string pool garbage collected in Java?

From Java 7 onwards, the Java String Pool is stored in the Heap space, which is garbage collected by the JVM.


1 Answers

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:

  1. Declare Set<String> StringConstantPool = new HashSet<String>();
  2. call String.intern()
  3. Add returned String value into this pool StringConstantPool
like image 181
anubhava Avatar answered Oct 06 '22 00:10

anubhava