Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class and interface initialization in java

Tags:

java

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

like image 924
overexchange Avatar asked Dec 08 '22 02:12

overexchange


1 Answers

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.

like image 157
TheLostMind Avatar answered Dec 11 '22 10:12

TheLostMind