What will the following code.s execution print to console?

public class Test {

    static int b = Test.a;
    static final int a = 3;
    
    public static void main(String... args) {
        System.out.println("a = " + a + ", b = " + b);
    }
    
}
Explanation

At first glance it might seem that the "a = 3, b = 0" answer choice is correct, since static fields are initialized in order of their declaration and not initialized value of a is assigned to the b field.

In fact, since the a field is a constant, then compiler immediately substitutes its value. I. e. first line compiles as

static int b = 3;

and the answer correct answer "a = 3, b = 3" is correct.

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Продовжуйте вивчати
тести з Java
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести