Below is the code,
class Z{
    static int peekj(){
        return j;
    }
    static int peekk(){
        return k;
    }
    static int i = peekj();
    static int h = peekk();
    static final int j = 1;
    static int k = 1;
}
public class ClassAndInterfaceInitialization {
    public static void main(String[] args) {
        System.out.println(Z.i);
        System.out.println(Z.h);
    }
}
After following the forward reference rule for static initialization, I see the output as:
1
0
After class Z is loaded & linked, In the initialization phase, variable  j being final is very firstly initialized with 1. variable k is also initialized with 1.
But the output gives 0 for variable k.
How do I understand this?
Note: Compiler actually replaces value of variable j wherever it is referenced following forward reference rules, unlike k
static final int will make j a compile-time constant. So, its value will be present and passed as part of the byte-code itself. So, j will be 1 when your class is being initialized.But k is is just static int, so its default value will be printed since your static initializer runs before the value of k is initialized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With