Please consider this code snippet:
private static void doSomething(Double avg, Double min, Double sd) {
final Double testMin;
if (avg != null) {
testMin = Math.max(min, avg - 3 * sd);
} else {
testMin = min;
}
System.out.println("testMin=" + testMin);
final Double verwachtMin = avg != null ? Math.max(min, avg - 3 * sd) : min;
System.out.println("verwachtMin=" + verwachtMin);
}
As far as I know (and for what my IDE can tell me), the variables testMin
and verwachtMin
should be equivalent.
As you might expect, I'd rather write the last 2 lines than the first 7. However, when I pass 3 null values to this method, I get an NPE on the calculation of the verwachtMin
variable.
Does anyone know how this can happen? Does the ternary operator evaluate the 2nd part, even when the condition is not true
?
(Java version 1.6.0_21)