Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way to convert Integer (may be null) to int in Java?

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?

like image 932
SparkAndShine Avatar asked Oct 22 '15 09:10

SparkAndShine


People also ask

How do I convert Integer to int in Java?

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.

Can we assign null to int in Java?

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.

Can null be assigned to int?

null can only be assigned to reference type, you cannot assign null to primitive variables e.g. int, double, float, or boolean.

What is the equivalent of null for int?

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.


1 Answers

With Java8 the following works, too:

Optional.ofNullable(integer).orElse(-1)
like image 141
Jens.Huehn_at_SlideFab.com Avatar answered Sep 28 '22 09:09

Jens.Huehn_at_SlideFab.com