1

Can anyone tell me why does Java throw a NullPointerException here?

Float x = <some condition> ? myObject.getSomeFloat() : 0.0f;
  • The method getSomeFloat returns Float.
  • Changing 0.0f to new Float(0) works fine.
Eran
  • 387,369
  • 54
  • 702
  • 768
bashan
  • 3,572
  • 6
  • 41
  • 58

1 Answers1

5

The type of this ternary operator is float. Therefore, if myObject.getSomeFloat() returns null, a NullPointerException is thrown when <some condition> is true and myObject.getSomeFloat().floatValue() is called in order to convert the Float to float.

JLS 15.25:

If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.

In your case, you have a primitive type - float - and the Boxed version of that float - Float. Therefore, the type of the conditional expression is the primitive type - float.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 1
    @almasshaikh No, you are wrong. Try `Float x = true ? (Float)null : 0.0f; System.out.println(x);` An arbitrary `null` reference is not the same scenario. – Eran Jan 01 '15 at 12:48
  • Wow, that's counterintuitive. (+1) – NPE Jan 01 '15 at 12:48
  • This answer is correct - the `getSomeFloat()` method must be returning null, which is auto unboxed... boom. Changing the other value to `Float` prevents the auto unbox - no boom. – Bohemian Jan 01 '15 at 12:54