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

24,137

Solution 1

Avoiding an exception is always better.

int i = integer != null ? integer.intValue() : -1;

Solution 2

With Java8 the following works, too:

Optional.ofNullable(integer).orElse(-1)

Solution 3

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);
Share:
24,137

Related videos on Youtube

SparkAndShine
Author by

SparkAndShine

For more about me, please refer to, Blog: sparkandshine.net GitHub: https://github.com/sparkandshine WeChat: SparkAndShine

Updated on January 19, 2020

Comments

  • SparkAndShine
    SparkAndShine over 4 years

    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?

    • S. Pauk
      S. Pauk over 8 years
      you shouldn't use assert in this case cause null is a valid execution path and could indeed happen in production
  • Kayaman
    Kayaman over 8 years
    Darn you and your fast fingers. I was going for the autoboxing way of int i = integer == null ? 0 : integer;.
  • S. Pauk
    S. Pauk over 8 years
    avoiding C legacy notation could also be considered to be a better way by some ppl
  • Eran
    Eran over 8 years
    @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?
  • Konstantin Yovkov
    Konstantin Yovkov over 8 years
    @Eran, by calling .intValue() you avoid the un-boxing and get the primitive value directly.
  • khelwood
    khelwood over 8 years
    @kocko .intValue() isn't avoiding unboxing; it is explicitly unboxing
  • Konstantin Yovkov
    Konstantin Yovkov over 8 years
    @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.
  • Snekse
    Snekse about 8 years
    How does NumberUtils or Guava not already have a method for this? They have defaultValue(primary, fallback) for so many things, but not this.
  • Kong
    Kong over 3 years
    This is the correct answer for modern Java as it can be done in one assignment. The ternary expression can't.