Java null to int Conditional Operator issue [duplicate]
Asked Answered
T

1

16

Possible Duplicate:
Tricky ternary operator in Java - autoboxing

We know that int roomCode = null; is not allowed by the compiler.

Then why the Code 1 doesn't give a compiler error, when Code 2 does.

Code 1:

int roomCode = (childCount == 0) ? 100 : null;

Code 2:

int roomCode = 0;
if(childCount == 0) roomCode = 100;
else roomCode = null; // Type mismatch: cannot convert from null to int
Turley answered 23/2, 2012 at 5:49 Comment(4)
maybe related to autoboxing but I don't see how...Vinegar
What does the null evaluate to when it takes that path?Nahtanha
From the JLS 15.25: If one of the second and third operands is of the null type and the type of the other is a reference type, then the type of the conditional expression is that reference type. So in your case it might consider return type of ?: operator as int.Equivoque
Before I post, I searched but couldn't find a duplicate. Thanx for the reference Joel. +1.Turley
V
11

I did a little debugging and found out that when evaluating

(childCount == 0) ? 100 : null;

the program calls the method valueOf of Integer to evaluate the null. It returns an Integer and as an Integer can be null (and not an int), it compiles. As if you were doing something like:

int roomCode = new Integer(null);

So it is related to autoboxing.

Vinegar answered 23/2, 2012 at 6:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.