Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static block initialization

This is a snippet of Java code:

static {        
    ture = 9;       
}
static int ture;
{ // instance block 
    System.out.println(":"+ture+":");           
}

How is that it compiles at all? Declaration of variable 'ture' has been performed after initialization. As far as I know static blocks and fields have been executed in the order they appear.

And now why is that value 9 within instance block has been printed 3 times? By the way, the instance of the class has been created 3 times. That is not a homework, I am learning Java for certification.

like image 372
uml Avatar asked Dec 06 '22 10:12

uml


2 Answers

Regarding your first question, static blocks are indeed processed in the order in which they appear, but declarations are processed first, before the static blocks are. Declarations are processed as part of the preparation of the class (JLS §12.3.2), which occurs before initialization (JLS §12.4.2). For learning purposes, the entire JLS §12 may be useful, as well as JLS §8, particularly §8.6 and JLS §8.7. (Thank you to Ted Hopp and irreputable for calling out those sections.)

There isn't enough information in your quoted code to answer your second question. (In any case, on SO it's best to ask one question per question.) But for instance:

public class Foo {
    static {     
        ture = 9;   
    }

    static int ture;

    {   // instance block   
        System.out.println(":"+ture+":");

    }

    public static final void main(String[] args) {
        new Foo();
    }
}

...only outputs :9: once, because only one instance has been created. It doesn't output it at all if you remove the new Foo(); line. If you're seeing :9: three times, then it would appear that you're creating three instances in code you haven't shown.

like image 122
T.J. Crowder Avatar answered Dec 20 '22 17:12

T.J. Crowder


The static initializers are executed in the order in which they appear and the declarations aren't executed at all, that's how they got their name. This is why your code compiles without problems: the class structure is assembled at compile time from the declarations, and the static blocks are executed at runtime, long after all the declarations have been processed.

like image 22
Marko Topolnik Avatar answered Dec 20 '22 17:12

Marko Topolnik