Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the constant pool (in Java classfile) indexed from 1 (and not 0)? What is the constant_pool[0] entry reserved for?

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.

like image 989
Curious Learner Avatar asked Jan 27 '23 03:01

Curious Learner


2 Answers

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:

  • The superclass of java/lang/Object
  • The name of a parameter with no name
  • The outer class for classes which are not the member of another class (i.e. top level classes, local classes, and anonymous classes)
  • The inner name of anonymous classes
  • The enclosing method for classes which are not immediately enclosed in a method
  • Version info for a module with no version info
  • Dependencies for a module with no dependency info
like image 70
Antimony Avatar answered Mar 05 '23 01:03

Antimony


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).

like image 28
John Bollinger Avatar answered Mar 04 '23 23:03

John Bollinger