Following are the code fragments which will compile without errors when inserted at //insert code here
A. Object x = t.findLarger(123, “456”);
B. int x = t.findLarger(123, new Double(456));
C. int x = t.findLarger(123, new Integer(456));
D. int x = (int) t.findLarger(new Double(123), new Double(456));
I tested this code and observed that A and C are compiling successfully.
Can anyone please explain this strange behaviour of code.
A) works because the return type is either going to be an Integer or a String which are both subtypes of Object
B) fails because you can't cast a Double to an int
C) works because you can cast an Integer to an int
D) fails for the same reason as B
This is not a Generics question but a question of casting...sneaky eh?
The programmer exam is quite specific between compiler and runtime errors - as we all know just because something compiles doesn't mean it is right or will run
is passing an int (123) and a String ("456") to the findLarger method, this is converted to an Integer and a String automatically by the compiler (AutoBoxing), as both Integer and String implement the Comparable interface this is fine and the method returns whichever of the 2 is appropriate depending on the implementation of Comparable (the compareTo part is where it will fail with the ClassCastException when it is run but the compiler doesn't know this)
if you run this code you get the following:
and this is because the compareTo implementation of Integer is:
By the way, I think the way to turn your runtime exception into a compile-time error is to declare it like this:
Because Integer implements Comparable<Integer>, and String implements Comparable<String>, option A will no longer compile because they can't be compared with each other. The problem with the example given is that's it's partly generic, but it hasn't gone all the way.
Matthew Brown wrote:By the way, I think the way to turn your runtime exception into a compile-time error is to declare it like this:
Because Integer implements Comparable<Integer>, and String implements Comparable<String>, option A will no longer compile because they can't be compared with each other. The problem with the example given is that's it's partly generic, but it hasn't gone all the way.
Hi,
Could you please explain this in a little more detail how this declaration would help the compiler to catch the Integer-String comparison, preferable plugging in Integer/String into the declaration.
TIA.
I've read about this kind of thing at the checkout counter. That's where I met this tiny ad:
a bit of art, as a gift, the permaculture playing cards