Home > Software design >  why is the Java constant_pool memort allocation defined as having size constant_pool_count-1
why is the Java constant_pool memort allocation defined as having size constant_pool_count-1

Time:10-19

The java class definition (docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html) looks like:

ClassFile {
    u4             magic;
    u2             minor_version;
    u2             major_version;
    u2             constant_pool_count;
    cp_info        constant_pool[constant_pool_count-1];
    u2             access_flags;
    u2             this_class;
    u2             super_class;
    u2             interfaces_count;
    u2             interfaces[interfaces_count];
    u2             fields_count;
    field_info     fields[fields_count];
    u2             methods_count;
    method_info    methods[methods_count];
    u2             attributes_count;
    attribute_info attributes[attributes_count];
}

But why is the constant_pool calculated as constant_pool_count-1? Why is it decreased by 1? I would expect it to be constant_pool[constant_pool_count] NOT constant_pool[constant_pool_count-1].

CodePudding user response:

Because according to the docu you posted:

The value of the constant_pool_count item is equal to the number of entries in the constant_pool table plus one

Therefore constant_pool[constant_pool_count] would result in an invalid index.

As to the reason behind the reason - I can only guess here. Presumably it's due to the choice of indexing beginning with 1 rather than 0.

CodePudding user response:

As you can see, constant_pool is indexed from 1 instead of 0, which is a bit against common sense, But this is for the meaning of "no reference to any constant value item" for data pointing to a constant pool index value in a particular case, which can be expressed with an index value of 0

  • Related