Wednesday, August 25, 2010

Cannot Widen and Box at the same time:

Courtesy of Sun Web Learning Center


 5. public class Ali {
 6.   public static void main(String[] args) {
 7.     // insert code here
 8.     jab(y);
 9.   }
10.   static void jab(Long x) {
11.     System.out.println("Long");
12.   }
13. }

And the following four code fragments:

I.   int y = 7;
II.  long y = 7;
III. Long y = 7;
IV.  Integer y = 7;

Which code fragments, inserted independently at line 7, will compile?

A Only fragment II.
B Only fragment III.
C Both fragments II and III.
D Fragments I, II, and III.
E Fragments II, III, and IV.
F All four fragments will compile.

A is correct. Fragment I would require both widening and boxing. Fragment IV would require widening from one wrapper type to another. Fragment III would compile if 7 had been 7L.

No comments:

Post a Comment