18

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
CODEBLACK
  • 1,239
  • 1
  • 15
  • 26
  • 6
    There will be many, many more strings in the constant pool---those that come from the JDK classes and any of your dependencies. Note that the string pool is filled at **class loading** time, and not when actual code which refers to the string constants is run. – Marko Topolnik Sep 27 '13 at 11:42
  • @MarkoTopolnik interesting point, I would not have assumed that strings defined in the JDK classes would have been loaded into the pool. – CODEBLACK Sep 27 '13 at 11:51
  • It is true for any class, including the JDK classes, once the class itself has been loaded. – user207421 Sep 27 '13 at 12:38

1 Answers1

10

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    The Javadoc has been wrong and indeed self-contradictory on this point forever. It can't be true both that the pool is 'initially empty' *and* that 'all string literals and constant-valued string expressions are interned', and it is also untrue that the String class is responsible for the latter. It is in fact wrong to describe that as interning at all. – user207421 Sep 27 '13 at 12:36
  • 3
    I believe by writing `initially empty` they mean to say that when JVM loads this pool is empty. – anubhava Sep 27 '13 at 12:42
  • 4
    It is not only private from OOP point of view, but actually [implemented as a native method](http://stackoverflow.com/questions/3323608/how-is-javas-stringintern-method-implemented). This means that it is not possible to access it even with a reflection. – om-nom-nom Sep 27 '13 at 12:47