Question 4
Back to Exercise
What is the output of the following Java program?
public class Main {
static int x = 10;
static { x += 5; System.out.print("A" + x + " "); }
static int y = x * 2;
static { y++; System.out.print("B" + y + " "); }
public static void main(String[] args) {
System.out.println("main " + x + " " + y);
}
}
- A A15 B31 main 15 31 Correct
- B main 15 31
- C A15 B30 main 15 30
- D B31 A15 main 15 31
Correct Answer: Option A
Static initialisers and blocks run top to bottom before main: x = 15, y = 30, then y = 31.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!