Java OCA OCP Practice Question 2560

Question

Given:

3. public class Main {  
4.   public static void main(String[] args) {  
5.     short a1 = 6;  
6.     new Main().go(a1);  
7.     new Main().go(new Integer(7));  
8.   }  //from   ww  w .jav a2s  .c o m
9.   void go(Short x) { System.out.print("S "); }  
10.   void go(Long x) { System.out.print("L "); }  
11.   void go(int x) { System.out.print("i "); }   
12.   void go(Number n) { System.out.print("N "); }  
13. } 

What is the result?

  • A. i L
  • B. i N
  • C. S L
  • D. S N
  • E. Compilation fails.
  • F. An exception is thrown at runtime.


B is correct.

Note

First, code written before Java 5 shouldn't be affected by new Java features like autoboxing, therefore widening is preferred to boxing, producing "i".

Second, you can't widen from one wrapper to another.

In this case, Integer is-Not-a Long, but Integer is-a Number.




PreviousNext

Related