Reputation: 3042
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:
string pool
refer to the pool of a constant string object in the constant pool?Upvotes: 24
Views: 14516
Reputation: 11
constans_pool(all constans, including Strings) is a data structure in class file(out of JVM). When class file is loaded into JVM, then constans_pool -> run-time constans_pool(General), in hotspot & SE8:
Upvotes: 1
Reputation: 120496
My questions are,
- 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 methodString.intern
.
Upvotes: 24
Reputation: 45654
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.
Upvotes: 3