Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

methods - java.lang.NullPointerException with boolean

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

I don't know what I'm doing wrong.

 public class Main {

    public static String bool(Boolean param){
        if(param == true){    (line 5)
            return "a";
        }else if(param == false){
            return "b";
        }
        return "c";

    }

    public static void main(String[] args){

        System.out.println(bool(true));
        System.out.println(bool(null)); (line 17)
        System.out.println(bool(false));


    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...