0

below code fails with NullPointerException somehow and I am not sure why:

import java.util.*;
public class MyClass {
    public static void main(String args[]) {
       Long x = null;
       Long test = (true) ? x : 0L; //Fails here with NullPointerException
    }
}

However, if i replace x with null in conditional operation, it works

import java.util.*;
public class MyClass {
    public static void main(String args[]) {
       Long x = null;
       Long test = (true) ? null : 0L; //WORKS - replaced x with null
    }

}

Can anybody help me understand whats going on here? or is it java bug.

sun2
  • 1,118
  • 1
  • 13
  • 17
  • No it is not duplicate – sun2 Feb 25 '19 at 17:43
  • 1
    How do you figure? `0L` is a `long`, so your first code block is treating `x` as a `long` and blowing up because its `null`. How is your case different? – azurefrog Feb 25 '19 at 17:45
  • 1
    For your case specifically, think of it like this: `Long test = (true) ? x : 0L;` is really being treated like `Long test = Long.valueOf(true ? x.longValue() : 0L)`, because the compiler decided that ternary type should be `long` rather than `Long`, where `x.longValue()` is throwing the NPE. But `Long test = (true) ? null : 0L` is being treated like this `Long test = (true) ? (Long) null : Long.valueOf(0L)` because the compiler is treating the ternary type as `Long`. – xtratic Feb 25 '19 at 17:49
  • Thank you. This does explain a lot. still confused as why it would use x.longValue() ? Return type is Long, not primitive type long. – sun2 Feb 25 '19 at 17:55
  • @sun2 when determining the result type of the ternary operator, the compiler does not look at the type of destination variable. – Henry Feb 26 '19 at 05:18

0 Answers0