I know that when I read the answer to this I will see that I have overlooked something that was under my eyes. But I have spent the last 30 minutes trying to figure it out m
Guava has a pretty elegant solution for this using MoreObjects.firstNonNull:
Integer someNullInt = null;
int myInt = MoreObjects.firstNonNull(someNullInt, 0);
Just in case you don't have Guava in your project, but already using Apache Commons, you might utilize Apache Lang3 with its ObjectUtils class.
The usage is basically the same as Guava:
Integer number = null;
int notNull = ObjectUtils.firstNonNull(number, 0);
Note, that this method in Guava library works faster, than in Apache. Here is a short comparison I just made on my laptop (Core i7-7500U 2.7 GHz), Oracle Java 8, multiple runs, JVM preheated, results are averaged:
╔══════════════╦══════╦══════╦════════╦══════╗
║ Library/Runs ║ 1000 ║ 1mln ║ 100mln ║ 1bln ║
╠══════════════╬══════╬══════╬════════╬══════╣
║ Apache ║ 1 ║ 30 ║ 782 ║ 9981 ║
║ Guava ║ 1 ║ 22 ║ 120 ║ 828 ║
╚══════════════╩══════╩══════╩════════╩══════╝
Results are in milliseconds. I don't think you often need to run this method for billions of times, but still, it is always good to have performance comparison
The problem with autounboxing null
values can be really annoying. In your example it's a combination of ternary operator result type inferring and autounboxing (the JLS should be consulted why it behaves like that)
But generally, you should try to avoid using wrapper types. Use int
instead of Integer
. If you need a special value meaning "no result", then you can use Integer.MAX_VALUE
for example.
Let's look at the line:
return y == null ? null : y.intValue();
In a ? :
statement, both sides of the :
must have the same type. In this case, Java is going to make it have the type Integer
. An Integer
can be null
, so the left side is ok. The expression y.intValue()
is of type int
, but Java is going to auto-box this to Integer
(note, you could just as well have written y
which would have saved you this autobox).
Now, the result has to be unboxed again to int
, because the return type of the method is int
. If you unbox an Integer
that is null
, you get a NullPointerException
.
Note: Paragraph 15.25 of the Java Language Specification explains the exact rules for type conversions with regard to the ? :
conditional operator.
The type of the return type is inferred by Java here. That is the issue ..
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.25
Here is the actual problem --
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, basically the compiler infers the return type of the conditional expression to be Integer and thats why it allows you to compile successfully.
EDIT : See rules in comments
This illustrates a problematic difference between the way a human reads code and a compiler reads code.
When you see a ternary expression, it's very possible for you to mentally split it into two parts, in the style of an if
/else
statement:
if (y == null)
return null;
else
return y.intValue();
You can see that this is invalid, as it results in a possible branch where a method defined to return an int
is actually returning null
(illegal!).
What the compiler sees is an expression, which must have a type. It notes that the ternary operation includes a null
on one side and an int
on the other; due to Java's autoboxing behavior, it then comes up with a "best guess" (my term, not Java's) as to what the expression's type is: Integer
(this is fair: it's the only type which could legally be null
or a boxed int
).
Since the method is supposed to return an int
, this is fine from the compiler's perspective: the expression being returned evaluates to an Integer
, which can be unboxed automatically.