Possible Duplicate:
Java static class initialization
in what order are static blocks and static variables in a class executed?
When I run this code the answer is 1, I thought it would be 2. What is the order of initialization and the value of k in each step?
public class Test {
    static {k = 2;}
    static int k = 1;
    public static void main(String[] args) {
        System.out.println(k);
    }
}
Edit 1: As a follow up to "k is set to default value" then why this next code doesn't compile? Theres an error "Cannot reference a field before it's defined".
public class Test {
    static {System.out.println(k);}
    static int k=1;
    public static void main(String[] args) {
        System.out.println(k);
    }
}
Edit 2: For some unknow to me reason it^ works when instead of "k" its "Test.k".
Thanks for all the answers. this will sufice :D
They are executed in the order that you write them. If the code is:
public class Test {
    static int k = 1;
    static {k = 2;}
    public static void main(String[] args) {
        System.out.println(k);
    }
}
then the output becomes 2.
The order of initialization is: ..the class variable initializers and static initializers of the class..., in textual order, as though they were a single block.
And the values (for your code) are: k = 0 (default), then it's set to 2, then it's set back to 1.
You can check that it's actually set to 2 by running the following code:
private static class Test {
    static {
        System.out.println(Test.k);
        k = 2;
        System.out.println(Test.k);
        }
    static int k = 1;
    public static void main(String[] args) {
        System.out.println(k);
    }
}
                        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