Java OCA OCP Practice Question 264

Question

What does the following output?

1:  public class MyClass { 
2:     public String first = "instance"; 
3:     public MyClass() { 
4:        first = "constructor"; 
5:     } // w  ww . j ava  2s  .  co  m
6:     { first = "block";  } 
7:     public void print() { 
8:        System.out.println(first); 
9:     } 
10:    public static void main(String... args) { 
11:      new MyClass().print();  
12:    } 
13: } 
  • A. block
  • B. constructor
  • C. instance
  • D. The code does not compile.


B.

Note

First line 2 runs and sets the variable using the declaration.

Then the instance initializer on line 6 runs.

Finally, the constructor runs.

Since the constructor is the last to run of the three, that is the value that is set when we print the result, so Option B is correct.




PreviousNext

Related