Question discussion

What is the output of the following Java program?public class Main { static int a = get(); static int b = 5; static int get() { return b +…

2388Medium DSSSB TGT Computer Science 0 replies

What is the output of the following Java program?

public class Main {
    static int a = get();
    static int b = 5;
    static int get() { return b + 1; }
    public static void main(String[] args) {
        System.out.println(a + " " + b);
    }
}
  • ACompilation error: illegal forward reference
  • B6 5
  • C0 5
  • D1 5
Correct answer: D

Explanation

Static initialisers run in textual order; when get() is called for a, the variable b still has its default value 0, so a = 1, and b is then set to 5.

Discussion 0

Nobody has replied yet. Start the discussion!