How java initializes static variables and static method? (With simple code)

I wonder how java initializes these static variables. Code that I cannot understand is shown by a hit:

public class Main {

static int first=test();
static int second=2;
static int third=test();

public static void main(String[] args) {

    System.out.println(first);
    System.out.println(second);
    System.out.println(third);

}


public static int test() {
    return second;
}

}

The result of the simple code below: 0 2 2

Should the compiler automatically ignore the non-executable method or is the static variable equal to 0 before it determines?

Sorry, you cannot find the exact description for Google.

+4
source share
4 answers

Java , . , , . , , 0, null false, . . , .

,

first = 0; // second hasn't been set yet
second = 2;
third = 2; // second has been set to 2.

, .

+4

.

// executing order top to bottom
static int first=test();//test() will return value of second still second is 0
static int second=2;//now second will be 2
static int third=test();//test() will return current value of second, which is 2

public static void main(String[] args) {

    System.out.println(first);// so this will be 0
    System.out.println(second); // this will be 2
    System.out.println(third); // this will be 2

}

public static int test() {
    return second;
}
0

, ,

public static int test() {
    System.out.println("Test exceuted")
    return second;
}

, , :

Test exceuted
Test exceuted
0
2
2

, , , 0 .

0

JVM:

. JVM (/) / . (/ ) - .

, , . test() ; second , (), 0. 2 - 0 2 2.

- .

0

Source: https://habr.com/ru/post/1584244/


All Articles