Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a static variable before declaring

Tags:

java

static

I'm learning Java and write the simple code below:

public class Test {

    private int a = b;  
    private final static int b = 10;

    public int getA() {
        return a;
    }
}

public class Hello {

    public static void main(String[] args) {
        Test test = new Test();
        System.out.println(test.getA());
    }

}

The result: 10. Well done! It run successfully and have no error.

Can anyone please explain why I can assign a static variable before declaring it?

like image 782
Dat Nguyen Avatar asked Dec 30 '14 09:12

Dat Nguyen


Video Answer


1 Answers

The assignment

private int a = b;  

takes place when you create a new instance of Test (just before the constructor is called).

The declaration and initialization of the static variable b, takes place before the instance is created, when the class is loaded.

The order of the statements doesn't matter, since static variables are always initialized first.

like image 63
Eran Avatar answered Oct 09 '22 12:10

Eran