16

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?

SparkAndShine
  • 17,001
  • 22
  • 90
  • 134

5 Answers5

25

With Java8 the following works, too:

Optional.ofNullable(integer).orElse(-1)
  • This is the correct answer for modern Java as it can be done in one assignment. The ternary expression can't. – Kong Nov 20 '20 at 13:39
20

Avoiding an exception is always better.

int i = integer != null ? integer.intValue() : -1;
Eran
  • 387,369
  • 54
  • 702
  • 768
  • 3
    Darn you and your fast fingers. I was going for the autoboxing way of `int i = integer == null ? 0 : integer;`. – Kayaman Oct 22 '15 at 09:28
  • 1
    avoiding C legacy notation could also be considered to be a better way by some ppl – S. Pauk Oct 22 '15 at 09:28
  • @kocko My original answer (before your edit) without `.intValue()` works fine (Java handles the auto-unboxing). Do you think calling `intValue` explicitly is more efficient? – Eran Oct 22 '15 at 09:31
  • @Eran, by calling `.intValue()` you avoid the un-boxing and get the primitive value directly. – Konstantin Yovkov Oct 22 '15 at 09:35
  • 4
    @kocko `.intValue()` isn't avoiding unboxing; it is _explicitly_ unboxing – khelwood Oct 22 '15 at 09:36
  • 1
    @khelwood, I don't agree. If you see the source of `Integer#intValue()` you can see that the method returns the nested `private final int value;`. So, by assigning `integer.intValue()` to an `int` doesn't trigger any boxing/unboxing features of the compiler. However, having `int i = integer;` _will_ actually force the compiler to do unboxing from `Integer` to `int`. That's why I find the explicit call to `.intValue()` a bit more efficient (even there's not much performance difference) and _readable_. – Konstantin Yovkov Oct 22 '15 at 09:37
  • How does NumberUtils or Guava not already have a method for this? They have defaultValue(primary, fallback) for so many things, but not this. – Snekse Mar 08 '16 at 23:04
3

Java 9 introduce Objects.requireNonNullElse, alternative solution in Java Vanilla (without external library):

Integer integerValue = null;
int intValue = Objects.requireNonNullElse(integerValue, 0);
jpep1
  • 210
  • 2
  • 8
2

If you already have guava in your classpath, then I like the answer provided by michaelgulak.

Integer integer = null;
int i = MoreObjects.firstNonNull(integer, -1);
Community
  • 1
  • 1
Snekse
  • 15,474
  • 10
  • 62
  • 77