Boolean sortAsc = Objects.nonNull(chooseRequest) ? chooseRequest.getSortAsc() : false;
This code will throw NPE exception, why?
chooseRequest is a DTO and chooseRequest.getSortAsc() will return null
but this one is ok
Boolean sortAsc = Objects.nonNull(chooseRequest) ? null : false;
I cannot understand, JVM is 11
When you have the expression
and the return type of
chooseRequest.getSortAsc()is defined asBoolean, then the "result" of this (boolean) conditional expression will be aboolean(the primitive type), as indicated in the table Table 15.25-B. Conditional expression type (Primitive 3rd operand, Part II):When
chooseRequest.getSortAsc()is returningnull, you will get aNullPointerExceptionbecause it tries to call thejava.lang.Boolean.booleanValue()method onnullto convert theBooleanvalue to abooleanvalue.However, when you have the expression
then the "result" of this (reference) condition expression will be a
Boolean(the wrapper class):(for a definition of
lub()see 4.10.4. Least Upper Bound. Also see What is lub(null, Double)?)No
NullPointerExceptionwill be thrown here because no method is called onnull.Overall, the
NullPointerExceptionis not coming from calling thegetSortAsc()method onnullas you might suspect, it's coming from a conversion ofnullto abooleanvalue. Interestingly, if you change your variable fromBoolean sortAsctoboolean sortAsc, your second code block will throw aNullPointerExceptionas well, since it tries to calljava.lang.Boolean.booleanValue()on the returnednullvalue (assumingObjects.nonNull(chooseRequest)returnedtrueat that time).