JVM Knowledge

Many numeric constants, as well as objects, fields, and methods, are accessed via the run-time constant pool of the current class. Object access is considered later (§3.8). Data of types int, long, float, and double, as well as references to instances of class String, are managed using the ldc, ldc_w, and ldc2_w instructions.

The ldc and ldc_w instructions are used to access values in the run-time constant pool (including instances of class String) of types other than double and long. The ldc_w instruction is used in place of ldc only when there is a large number of run-time constant pool items and a larger index is needed to access an item. The ldc2_w instruction is used to access all values of types double and long; there is no non-wide variant.

Integral constants of types byte, char, or short, as well as small int values, may be compiled using the bipush, sipush, or iconst_<i> instructions (§3.2). Certain small floating-point constants may be compiled using the fconst_<f> and dconst_<d> instructions.

In all of these cases, compilation is straightforward. For instance, the constants for:

void useManyNumeric() {
    int i = 100;
    int j = 1000000;
    long l1 = 1;
    long l2 = 0xffffffff;
    double d = 2.2;
    ...do some calculations...
}

are set up as follows:

Method void useManyNumeric()
0   bipush 100   // Push small int constant with bipush
2   istore_1
3   ldc #1       // Push large int constant (1000000) with ldc
5   istore_2
6   lconst_1     // A tiny long value uses small fast lconst_1
7   lstore_3
8   ldc2_w #6    // Push long 0xffffffff (that is, an int -1)
        // Any long constant value can be pushed with ldc2_w
11  lstore 5
13  ldc2_w #8    // Push double constant 2.200000
        // Uncommon double values are also pushed with ldc2_w
16  dstore 7
...do those calculations...