Wednesday, August 25, 2010

Widen before Box: WideLoad.java

Courtesy of Sun Web Learning Center


Given:

1. class WideLoad {
2.   public static void main(String [] args) {
3.     float f = 3.14f;
4.     new WideLoad().doIt(f);
5.   }
6.   void doIt(Float f) {
7.     System.out.println("Float");
8.   }
9.   void doIt(double d) {
10.     System.out.println("double");
11.   }
12. }

What is the result?


A Float
B double
C Compilation fails.
D The output is not predictable.
E An exception is thrown at runtime.

B is correct. The JVM will widen before it boxes, so the method on line 9 is invoked.

No comments:

Post a Comment