Initializing a class and interface in 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(Zi); System.out.println(Zh); } } 

After executing the direct reference rule for static initialization, I see the output as:

 1 0 

After class Z loaded and connected, at the initialization stage, the variable j , which is final , is first initialized with 1 . the variable k also initialized with 1 .

But the output gives 0 for the variable k .

How do I understand this?

Note. The compiler actually replaces the value of the variable j wherever it is referenced according to direct referencing rules, unlike k

+4
source share
3 answers

"j" is a constant, so when the code compiles, j is replaced by number 1 in the entire program. So if you were an alien and you could read the byte code, the code would look like this:

  static int peekj(){ return 1;// j is replaced by the Actual Number 1 } 

Also, "static variables are initialized when the class is loaded" So, when the class is loaded, the following statements are executed sequentially

  static int i = peekj(); // Executed First, as peekJ() directly returns 1 so i is equal to 1 static int h = peekk(); // Executed Second, Now peekk() returns "THE VALUE OF k" which is not set yet ie default value of int is given 0(zero) //So h is equal to 0 static final int j = 1; // This statement doesn't exist as all j are replaced with actual Number 1 when we compiled java to .class static int k = 1; // Executed last, So now the value of 'k' is being set, after the value of 'h' has already been set to zero 

Note: Do this to get the output 1 and 1 ie i = 1 and h = 1; since the value of k is first set to 1.

  static int k = 1; static int i = peekj(); static int h = peekk(); static final int j = 1; 
+3
source

static final int will make j compile time constant. Thus, its value will be present and transmitted as part of the byte code itself. So j will be 1 when your class is initialized. But k is just a static int , so its default value will be printed, since your static initializer starts before the k value is initialized.

+6
source

You are trying to access k before it is initialized, therefore it is 0. ( h initialized before peekk() to k , therefore peekk() returns 0, because the fields are initialized from top to bottom.) j is final, therefore it is executed first; before declaring i , so i gets the value j or 1.

The following is the relevant Oracle documentation:

Then execute either initializers of the class variable, and initializers of the static class, or initializers of the interface fields, in textual order, as if they were a single block.

+5
source

All Articles