java.lang.NullPointerException with boolean

后端 未结 4 1971
长情又很酷
长情又很酷 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:40

    You used the Boolean instead of boolean. Boolean is a class, which means you can assign objects to it. In your case, you passed in a null, which is then assigned to param. You then tried to use param, which of course resulted in a NullPointerException.

    You can:

    • Get rid of the line bool(null)
    • Change Boolean to boolean in the parameters for bool()
    • Add an else if for when param is null
    0 讨论(0)
  • 2020-12-01 21:46

    null cannot be auto-unboxed to a primitive boolean value, which is what happens when you try to compare it with true. In

    param == true
    

    The type of true is boolean, therefore the left-hand operand must also be a boolean. You are passing in a Boolean, which is an object, but can be auto-unboxed to boolean.

    Therefore this is equivalent to

    param.booleanValue() == true
    

    Clearly, if param is null, the above throws NullPointerException.

    To avoid the hidden pitfalls of auto-unboxing, you could instead work with the Boolean objects:

    if (Boolean.TRUE.equals(param))
      return "a";
    if (Boolean.FALSE.equals(param))
      return "b";
    return "c";
    
    0 讨论(0)
  • 2020-12-01 21:48

    So your program must be something like this.

    public class BooleanBug {
    
        public static String bool(Boolean param) {
            if ((null != param) && param.booleanValue() == true) {
                return "a";
            } else if ((null != param) && param.booleanValue() == false) {
                return "b";
            }
            return "c";
    
        }
    
        public static void main(String[] args) {
    
            System.out.println(bool(true));
            System.out.println(bool(null));
            System.out.println(bool(false));
    
        }
    }
    
    0 讨论(0)
  • 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";
    }
    
    0 讨论(0)
提交回复
热议问题