0

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

shodz
  • 344
  • 3
  • 13

2 Answers2

1

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.

Koenigsberg
  • 1,726
  • 1
  • 10
  • 22
  • thanks for the reply @Koenigsberg. But if you look at the other arrays it is the size of the count. For example interfaces[interfaces_count]. Why would the constant_pool_count be larger by one then necessary? – shodz Oct 18 '22 at 14:02
  • I think I might know. I have done a bit more looking up. Part of the constant pool is the count of the constant pool. Because the constant pool has the value, constant_pool_count - 1 is the number of remaining values in the constant pool. The constant_pool[constant_pool_count-1 ] is optimization. – shodz Oct 18 '22 at 14:08
0

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