0

In the following test, the getDummyAge() method should not be evaluated, because testage variable is always null.

public class IntegerTest {
    @Test
    public void intergerTestFailure() {
        Integer testage = null;
        Integer age = (testage != null) ? getDummyAge() : testage;
    }

    private int getDummyAge() {
        return 0;
    }
}

Though this throws an exception:

java.lang.NullPointerException at my.IntegerTest.intergerTestFailure(IntegerTest.java:18) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566)

Is this a jdk bug?

membersound
  • 81,582
  • 193
  • 585
  • 1,120

1 Answers1

1
Integer age = (testage != null) ? getDummyAge() : testage;

is equivalent to

Integer age = Integer.valueOf((testage != null) ? getDummyAge().intValue() : testage);

because numeric second and third operands of differing types undergo binary numeric promotion; the result of the conditional operator is int, which then has to be boxed back to Integer for the assignment.

This is as specified.

If you want to avoid the NPE, box the int explicitly:

Integer age = (testage != null) ? Integer.valueOf(getDummyAge()) : testage;

Boxed numerical operands of the same type are not unboxed.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243