We recently ran into a bug in production that I found to be very interesting. My longtime understanding is that a Java boolean can only be false, or true. However, it seems in a Ternary Operator it can ultimately resolve to null, and it never produced a compile error, and built all the way to production. I'm very suprised the following code does not generate a compile error. Does anyone know why it compiles just fine? Imho it should not compile! The value it ultimately resolves to is a native boolean.
boolean por = (str == null || str.length() == 0) ? null : "true".equalsIgnoreCase(str);
Does anyone know why it compiles just fine?
Ultimately, because of autoboxing / autounboxing.
When the compiler processes a ternary expression, it uses the second and third operands to choose the result type of the expression. In your case, the second has null type and the third has (primitive) boolean type. These are not directly compatible, but because of autoboxing, both are compatible with type Boolean. The result of the expression therefore has type Boolean, which does support null.
Because of autounboxing, it is allowed to assign a value of type Boolean to a variable of type boolean, but this will fail with a NullPointerException in the event that the value being assigned is null, just as if you had invoked the booleanValue() method on it. I presume that this is the error you observed in production.
This is one of the gotchas of autoboxing.