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.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes