10

There is the following code:

Integer time = 12;
Double lateTime = 12.30;
Boolean late = false;
Double result = late ? lateTime : time;  //Why here can I assign an Integer to a Double?
System.out.println(result);

It prints:

12.0

This one doesn't compile. Why?

Integer time = 12;
Double lateTime = 12.30;
Double result = time;      //Integer cannot be converted to Double
System.out.println(result);
Davide
  • 1,931
  • 2
  • 19
  • 39
  • Double result = time+1.0; would also compile – Gonen I Jan 23 '17 at 10:31
  • Possible duplicate of [Java autoboxing and ternary operator madness](http://stackoverflow.com/questions/25417438/java-autoboxing-and-ternary-operator-madness) – Tom Feb 14 '17 at 22:35

1 Answers1

12

The differences are due to the ternary operator behaviour in Java.


The ternary conditional case:

In the expression late ? lateTime : time, Java will auto-unbox exactly one of the arguments (according to the value of late) to its respective primitive type. (You can observe this by setting time to null and late to true: a NullPointerException is not thrown. The same applies when setting lastTime to null and late to false.)

If the value of the expression will be time, then this is widened to a double.

In either case, the resulting double is auto-boxed to a Double in assigning it to result.


The simple assignment case:

In writing Double result = time;, Java disallows this as it expects you to be more explicit.


Personally I find the mechanism of the Java ternary conditional operator with respect to the boxed primitive types to be one of the most pernicious parts of the language.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Ok, but in the first exemple 'result' is always a Double or is casted into an Integer? – Davide Jan 23 '17 at 10:27
  • @Eran: I've been more explicit about the precise mechanism, and added the NPE sting. – Bathsheba Jan 23 '17 at 10:30
  • 1
    Double result = time+1.0; would also compile. In fact so would + 0.0; And +1 just for the use of the word pernicious. – Gonen I Jan 23 '17 at 10:31
  • 1
    @Eran: Yes I was inaccurate. I've also checked, and amended the answer. – Bathsheba Jan 23 '17 at 10:38
  • @Eran: I was still wrong, only *one* argument is auto-unboxed. I think I have it right now. – Bathsheba Jan 23 '17 at 10:43
  • This answer looks correct. The [JLS](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25) official specification of the conditional operator is very complicated indeed. – Klitos Kyriacou Jan 23 '17 at 11:10