String pool vs Constant pool

Let's look at the folloing code snippet:

  String s1 = "Hello";
  String s2 = "Hello"; 

Both variables refer to the same object due to interning. Since strings are immutable, only one object is created and both refer to the same object.

A constant pool is also something, which holds all the constants (integer, string, etc.) that are declared in a class. It is specific to each class.

 System.out.println("Hello");  // I believe this Hello is different from above.

Questions:

  1. Does string pool refer to the pool of a constant string object in the constant pool?
  2. If yes, is String pool common throughout the whole application or specific to a class?

Solution 1:

My questions are,

  1. Does string pool refers to the pool of constant string object in the constant pool?

No.

"Constant pool" refers to a specially formatted collection of bytes in a class file that has meaning to the Java class loader. The "strings" in it are serialized, they are not Java objects. There are also many kinds of constants, not just strings in it.

See Chapter 4.4 the constant pool table

Java Virtual Machine instructions do not rely on the run-time layout of classes, interfaces, class instances, or arrays. Instead, instructions refer to symbolic information in the constant_pool table.

In contrast, the "String pool" is used at runtime (not just during class loading), contains only strings, and the "strings" in the string pool are java objects. The "string pool" is a thread-safe weak-map from java.lang.String instances to java.lang.String instances used to intern strings.

Chapter 3.10.5. String Literals says

A string literal is a reference to an instance of class String (§4.3.1, §4.3.3).

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

Solution 2:

There is only one string pool, and all string literals are automatically interned.
Also, there are other pools for autoboxing and such.

The constant pool is where those literals are put for the class.