Java OCA OCP Practice Question 2827

Question

Given:

2. class Main {  
3.   static StringBuffer s;  
4.   public static void main(String[] args) {  
5.     Integer i = new Integer(42);  
6.     for(int j = 40; j < i; i--)  
7.       switch(i) {  
8.         case 41: s.append("41 ");  
9.         default: s.append("def ");  
10.         case 42: s.append("42 ");  
11.       }  //w  w  w  . j a v a 2  s.co  m
12.     System.out.println(s);  
13. } } 

What is the result?

  • A. 41 def
  • B. 41 def 42
  • C. 42 41 def 42
  • D. An exception is thrown at runtime.
  • E. Compilation fails due to an error on line 6.
  • F. Compilation fails due to an error on line 7.


D is correct.

Note

A NullPointerException is thrown because no instance of StringBuffer was ever created.

If the StringBuffer had been created, autoboxing allows the Integer to be used in the for and the switch, and the switch logic would produce the output in answer C.




PreviousNext

Related