What do you think that the following code snippet will print?
Object o = true ? new Integer(1) : new Double(2.0);
System.out.println(o);
Yes! It will print:
1.0
What? 1.0? But I have assigned an
Integer
to my
o
variable. Why does it print 1.0? It turns out that there is a subtle little specification section in the JLS’s
§15.25, which specifies the ternary operator. Here’s what is applied to the above:
The type of a conditional expression is determined as follows:
- […]
- Otherwise, if the second and third operands have types that are convertible (§5.1.8) to numeric types, then there are several cases:
- […]
- Otherwise, binary numeric promotion (§5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.
Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).
Binary numeric promotion may implicitly perform unboxing conversion! Eek! Who would have expected this? You can get a NullPointerException from auto-unboxing, if one of the operands is
null
, the following will fail
Integer i = new Integer(1);
if (i.equals(1))
i = null;
Double d = new Double(2.0);
Object o = true ? i : d; // NullPointerException!
System.out.println(o);
Obviously (obviously !?) you can circumvent this problem by casting numeric types to non-numeric types, e.g.
Object
Object o1 = true
? (Object) new Integer(1)
: new Double(2.0);
System.out.println(o1);
The above will now print
1
Credits for discovery of this gotcha go to Paul Miner, who has explained this more in detail
here on reddit.
Like this:
Like Loading...
Published by lukaseder
I made jOOQ
View all posts by lukaseder
http://javax0.wordpress.com/2013/09/18/something-you-did-not-know-about-the-ternary-operator/
Hah, yes. Awesome, so it actually happened to you! :-) This is really more of a JavaScript-sort-of behaviour!
I was hunting it a half day a year ago developing ScriptBasic for Java.
Try to approach the logic of the ternary operator a bit different and think of it as a numeric operator instead of ‘if’ statement. In that case it is logical. Very old school, but that is we love Java for. It is old school. :-D
I cannot exactly agree with loving Java for this particular quirk ;-)
http://lars-lab.jpl.nasa.gov/JPL_Coding_Standard_Java.pdf
R40 recommendatioin. Forgive me for not citing here whole. Excerpt:
R40 use one result type in conditional expressions
…
Rationale
The rules for determining the result type of a conditional expression are very complex and may result in surprises.
Thanks, great link! I shall read through that document, eventually!
Object o1 = true ? (Object) i : d;
System.out.println(o1);
This one also gives “null” :)