java.lang.NullPointerException with boolean

后端 未结 4 1972
长情又很酷
长情又很酷 2020-12-01 21:01

I wrote a realy simple code based on another question and here it is:

It throws me an error

java.lang.NullPointerException line 5 and 17

<
4条回答
  •  既然无缘
    2020-12-01 21:59

    Your code compares a java.lang.Boolean instance with a primitive boolean, which means unboxing the java.lang.Boolean. Since null can't be unboxed, a NullPointerException is thrown.

    You could work around this by using the built in constants Boolean.TRUE and Boolean.FALSE:

    public static String bool(Boolean param) {
        if (Boolean.TRUE.equals(param)) {
            return "a";
        } else if (Boolean.FALSE.equals(param)) {
            return "b";
        }
        return "c";
    }
    

提交回复
热议问题