Reputation: 463
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.
Upvotes: 6
Views: 1565
Reputation: 39451
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
Upvotes: 12
Reputation: 180286
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).
Upvotes: 1