LearnFrenzy
Sign in Take a free test

Constructors and the this Keyword · Predict the Output · Question 5

Instance blocks, fields and the constructor Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
class Order {
    { System.out.print("block1 "); }
    int x = init();
    Order() { System.out.print("ctor "); }
    { System.out.print("block2 "); }

    int init() { System.out.print("field "); return 1; }
}

public class Main {
    public static void main(String[] args) {
        new Order();
        new Order();
    }
}
  • A block1 field block2 ctor block1 field block2 ctor Correct
  • B ctor block1 field block2 ctor block1 field block2
  • C block1 block2 field ctor block1 block2 field ctor
  • D field block1 block2 ctor field block1 block2 ctor
Correct Answer: Option A

Instance blocks and field initialisers run in source order, before the constructor body, for every object.

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