javaperformancebooleannullable

Java check if boolean is null


How do you check if a boolean is null or not? So if I know hideInNav is null. How do I stop it from further executing? Something like the below doesn't seem to work but why?

boolean hideInNav = parent.getProperties().get("hideInNav", false);
String hideNavigation = hideInNav != null ? hideInNav : "";

Solution

  • boolean can only be true or false because it's a primitive datatype (+ a boolean variables default value is false). You can use the class Boolean instead if you want to use null values. Boolean is a reference type, that's the reason you can assign null to a Boolean "variable". Example:

    Boolean testvar = null;
    if (testvar == null) { ...}