Java OCA OCP Practice Question 3078

Question

Given:

2. class Shape {  
3.   static String s = "";  
4.   static { s += "sb1 "; }  
5.   Shape() { s += "e "; }  
6. }  //  ww  w  .  j a va 2  s.co m
7. public class Main extends Shape {    
8.   Main() {  
9.     s += "c4 ";  
10.     new Shape();  
11.   }  
12.   static {   
13.     new Main();  
14.     System.out.print(s);  
15.   }  
16.   { s += "i "; }  
17.   public static void main(String[] args) { }  
18. } 

And given the command-line invocation "java Main", what is the result?

  • A. e c4 i
  • B. e i c4
  • C. e sb1 i c4
  • D. sb1 e i c4 e
  • E. sb1 e c4 i e
  • F. Compilation fails.
  • G. A StackOverflowError is thrown.
  • H. An exception other than StackOverflowError is thrown.


D is correct.

Note

Static init blocks run once, when a class is first loaded.

Instance init blocks run after a constructor's call to super(), but before the rest of the constructor runs.

It's legal to invoke new() from within a constructor, and when a subclass invokes new() on a superclass no recursive calls are implied.




PreviousNext

Related