An Integer
can be null
. I convert an Integer
to an int
by:
Integer integer = null;
int i;
try {
i = integer.intValue();
}
catch (NullPointerException e) {
i = -1;
}
Is there a better way?
For converting Integer to int in Java explicitly, you can utilize the “intValue()” method of the Java “Integer” class. It takes no arguments and gives a primitive value as an output.
Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.
null can only be assigned to reference type, you cannot assign null to primitive variables e.g. int, double, float, or boolean.
A nullable of type int is the same as an ordinary int plus a flag that says whether the int has a value or not (is null or not). All the rest is compiler magic that treats "null" as a valid value.
With Java8 the following works, too:
Optional.ofNullable(integer).orElse(-1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With