From the JVM specs (Chapter 4.1 "The ClassFile structure"), it is stated that "The constant_pool table is indexed from 1 to constant_pool_count - 1."
I'm curious why they're skipping [0] and what is this entry reserved for.
They skipped index 0 so that it can be used for cases where you would normally reference a constant pool entry, but instead want to indicate "nothing". It is the constant pool equivalent of a null pointer.
The most notable use for index 0 is for "catch all" exception handlers. An exception handler can either point to the constant pool entry for the class of exceptions it wants to handle, or just use index 0 to catch everything (this is equivalent to catching java/lang/Throwable
). In practice, the compiler will generate catch all exception handlers to implement finally
, synchronized
blocks, and the cleanup portions of try with resources, among other things.
Other uses for index 0 include:
java/lang/Object
There is no reserved entry. "[I]ndexed from 1" means that the first entry in the constant pool corresponds to index 1, so there isn't any constant_pool[0]. Rather, there is a reserved index, 0, that is known with certainty to not be a valid index into the constant pool.
Documented uses for that reserved index seem to be rare, but at least section 4.7.24 specifies a use: method parameters' names are represented by indexes into the constant pool, and for unnamed parameters, that index is given as 0.
Note also that the name constant_pool_count
is misleading. The specification explicitly says that there are only constant_pool_count - 1
entries in the constant pool (see the structure declaration at the top of section 4.1, and compare to some of the other members).
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