0

When I execute the following code, NullPointerException occurs:

public static Integer getProperty(String name, Integer defaultValue) {
    String value = null;
    try {
        return (value != null) ? Integer.parseInt(value) : defaultValue;
    } catch (NumberFormatException e) {
        return defaultValue;
    }
}

public static void main(String[] args) {
    getProperty("unit", null);
}

Can somebody explain me why this is happening?

  • first NullPointer are clearly defined. 2nd which line? any stacktrace? Normaly should be closed because [what´s a nullpointer](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – LenglBoy Oct 25 '17 at 12:28
  • 1
    I look's like you are always having null in value, you are never initializing it to a value – Venkatesh Konatham Oct 25 '17 at 12:29
  • 1
    See the duplicate question for the answer. In order to fix your snippet, you can use `Integer.valueOf(value)` instead. – Alexis C. Oct 25 '17 at 12:31
  • Apparently it tries to auto-unbox the defaultValue as the left side of the ternary operator is `int`. Then it would auto-box it to return an `Integer`. If you do as Alexis said, you'll have `Integer` on both, thus no unboxing happens. – Vlasec Oct 25 '17 at 12:36
  • @AlexisC., thank you very much! – Andrei Mihuț Oct 25 '17 at 12:37
  • Just a suggestion: if you are using an IDE like Eclipse you can turn on 'INFO' on autoboxing/unboxing, it will underline you places in code where it happens, avoiding such questions in the future. – Shadov Oct 25 '17 at 12:37
  • A NullPointerException happening while unboxing is pretty hideous, with no apparent de-referencing happening in the code. I remember it confusing multiple coworkers in the past, and me as well. Now you know, and you won't be so surprised next time :) – Vlasec Oct 25 '17 at 12:38

0 Answers0