You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeWar计数绵羊问题出现NullPointerException的原因咨询

Why does 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:

  1. Automatic unboxing triggers the NPE in your initial code
    Boolean is a wrapper class for the primitive boolean type. When you write if(sheep) directly, the JVM automatically does unboxing: it calls sheep.booleanValue() to convert the Boolean object to a primitive boolean.

    If sheep is null, you're trying to call a method on a non-existent object—this immediately throws a NullPointerException. Worse, your else if(sheep == null) branch never runs because the error gets thrown before the code reaches it.

  2. Short-circuit && blocks the invalid unboxing
    The condition sheep != null && sheep uses Java's short-circuit logical AND operator (&&). Here's how it keeps things safe:

    • First, it checks sheep != null. If this is false (meaning sheep is null), the operator stops evaluating the rest of the condition—there's no point, since false && anything is always false.
    • Only if sheep != null is true does it proceed to evaluate sheep, which safely unboxes the non-null Boolean object to its primitive value.
  3. Fixing your original logic order
    Your initial code had the check order backwards: you tried verifying the Boolean value first, then handling null. 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 && sheep is more concise and idiomatic for this kind of check.


内容的提问来源于stack exchange,提问作者616Hz_lim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 19:22:44