LearnFrenzy
Sign in Take a free test

Static and Final Keywords · Predict the Output · Question 4

Several static blocks and field initialisers Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

What is the output of the following Java program?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links