Java.lang.NullPointerException with boolean

I wrote really simple code based on another question, and here it is:

It gives an error

java.lang.NullPointerException lines 5 and 17

I do not know what I am 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)); } } 
+9
source share
4 answers

null cannot be automatically unpacked with a primitive boolean value, which is what happens when you try to compare it to true . IN

 param == true 

true is boolean , so the left operand must also be boolean . You pass a boolean , which is an object, but can be automatically unboxed to boolean .

Therefore it is equivalent

 param.booleanValue() == true 

It is clear that if param is null , then a NullPointerException .

To avoid the hidden traps of automatic unlocking, you could work with boolean objects:

 if (Boolean.TRUE.equals(param)) return "a"; if (Boolean.FALSE.equals(param)) return "b"; return "c"; 
+25
source

Your code compares an instance of java.lang.Boolean with a primitive boolean , which means unpacking java.lang.Boolean . Since null cannot be unpacked, a NullPointerException thrown.

You can get around this 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"; } 
+1
source

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

You can:

  • Get rid of the string bool(null)
  • Change Boolean to Boolean in bool() options
  • Add else if param has null
0
source

So your program should 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
source

Source: https://habr.com/ru/post/1202497/


All Articles