Search code examples
javajvmbytecode

Can not see integer value in constant pool


Here is simple class.

public class Test{
    private int a = 10;
    private float b = 20.0F;
}

Using javap -v -l Test.class command to see the structure of class file. In Constant pool section, I should see all constants of the class. Nevertheless, I can find float value is 20.0f, but can not find int value.

public class Test
  minor version: 0
  major version: 52
  flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
   #1 = Methodref          #6.#17         // java/lang/Object."<init>":()V
   #2 = Fieldref           #5.#18         // Test.a:I
   #3 = Float              20.0f
   #4 = Fieldref           #5.#19         // Test.b:F
   #5 = Class              #20            // Test
   #6 = Class              #21            // java/lang/Object
   #7 = Utf8               a
   #8 = Utf8               I
   #9 = Utf8               b
  #10 = Utf8               F
  #11 = Utf8               <init>
  #12 = Utf8               ()V
  #13 = Utf8               Code
  #14 = Utf8               LineNumberTable
  #15 = Utf8               SourceFile
  #16 = Utf8               Test.java
  #17 = NameAndType        #11:#12        // "<init>":()V
  #18 = NameAndType        #7:#8          // a:I
  #19 = NameAndType        #9:#10         // b:F
  #20 = Utf8               Test
  #21 = Utf8               java/lang/Object
{
  public Test();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=2, locals=1, args_size=1
         0: aload_0
         1: invokespecial #1                  // Method java/lang/Object."<init>":()V
         4: aload_0
         5: bipush        10
         7: putfield      #2                  // Field a:I
        10: aload_0
        11: ldc           #3                  // float 20.0f
        13: putfield      #4                  // Field b:F
        16: return
      LineNumberTable:
        line 1: 0
        line 2: 4
        line 3: 10
}
SourceFile: "Test.java"

As per the doc https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.4-140

I should see CONSTANT_Integer in constant pool.


Solution

  • There are special instructions for loading small integer values (iconst_x for values from -1 to 5, bipush x for byte values and sipush x for short values).

    The constant pool is only used for integer values outside of this range, i.e. for numbers less than -32768 or greater than 32767.