java - Where is the NullPointerException coming from? -
i'm trying write method converts 2 digit number 2000 + number, returns other numbers , returns null when null passed argument.
this implementation works intended
private integer convertto4digits(integer modelyear) { boolean istwodigit = modelyear != null && modelyear < 100; if (istwodigit) { return 2000 + modelyear; } else { return modelyear; } }
but 1 fails npe in return statement when called null.
private integer convertto4digits(integer modelyear) { return (modelyear != null && modelyear < 100) ? (2000 + modelyear) : modelyear; }
or bug? i'm using eclipse keple jdk 1.7.0_04
i think answer can found in chapter 15.25 of jls
if 1 of second , third operands of primitive type t, , type of other result of applying boxing conversion (§5.1.7) t, type of conditional expression t.
so when either second or third operand primitive type expression's type primitive. if pass null
reference branch : modelyear
executed. since 1 operand primitive must unboxed. causes npe.
you can see if take @ generated byte code
private convertto4digits(ljava/lang/integer;)ljava/lang/integer; l0 linenumber 46 l0 aload 1 ifnull l1 aload 1 invokevirtual java/lang/integer.intvalue()i bipush 100 if_icmpge l1 sipush 2000 aload 1 invokevirtual java/lang/integer.intvalue()i iadd goto l2 l1 linenumber 47 l1 aload 1 invokevirtual java/lang/integer.intvalue()i l2 linenumber 46 l2 invokestatic java/lang/integer.valueof(i)ljava/lang/integer; areturn
your own answer solves problem because casting second operand integer
(modelyear != null && modelyear < 100) ? (integer) (2000 + modelyear) : modelyear;
and therefore neither second nor thrid operand of primitive type. rule of jls posted above not applied , npe gone.
Comments
Post a Comment