CodeWar计数绵羊问题出现NullPointerException的原因咨询
if(sheep) throw NullPointerException but if(sheep != null && sheep) works? Problem Context
I'm working on the "Counting Sheep" problem on CodeWars, which asks to count the number of sheep (represented by true values) in a Boolean array (ignoring false and null). My input array and initial code are as follows:
Input array:
Boolean[] array1 = {true, true, true, false, true, true, true, true , true, false, true, false, true, false, false, true , true, true, true, true , false, false, true, null };
Initial code (throws NullPointerException when encountering null):
public class Counter { public int countSheeps(Boolean[] arrayOfSheeps) { int sumOfSheep = 0; for(Boolean sheep:arrayOfSheeps){ if(sheep){ sumOfSheep++; } else if(sheep == null){ continue; } } return sumOfSheep; } }
When I change the condition to if(sheep != null && sheep), the code runs without errors. I want to understand why this happens.
Explanation
This is a classic issue caused by autoboxing/unboxing and short-circuit evaluation in Java—let's break it down step by step:
Automatic unboxing triggers the NPE in your initial code
Booleanis a wrapper class for the primitivebooleantype. When you writeif(sheep)directly, the JVM automatically does unboxing: it callssheep.booleanValue()to convert theBooleanobject to a primitiveboolean.If
sheepisnull, you're trying to call a method on a non-existent object—this immediately throws aNullPointerException. Worse, yourelse if(sheep == null)branch never runs because the error gets thrown before the code reaches it.Short-circuit
&&blocks the invalid unboxing
The conditionsheep != null && sheepuses Java's short-circuit logical AND operator (&&). Here's how it keeps things safe:- First, it checks
sheep != null. If this isfalse(meaningsheepisnull), the operator stops evaluating the rest of the condition—there's no point, sincefalse && anythingis alwaysfalse. - Only if
sheep != nullistruedoes it proceed to evaluatesheep, which safely unboxes the non-nullBooleanobject to its primitive value.
- First, it checks
Fixing your original logic order
Your initial code had the check order backwards: you tried verifying the Boolean value first, then handlingnull. To make it work without the short-circuit operator, you'd need to reverse the order:if(sheep == null) { continue; } else if(sheep) { sumOfSheep++; }But using
sheep != null && sheepis more concise and idiomatic for this kind of check.
内容的提问来源于stack exchange,提问作者616Hz_lim

