Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java null to int Conditional Operator issue [duplicate]

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
like image 754
namalfernandolk Avatar asked Feb 23 '12 05:02

namalfernandolk


1 Answers

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.

like image 115
talnicolas Avatar answered Sep 30 '22 07:09

talnicolas