A method receives a Boolean reference and must set it to false if null. Which code accomplishes this correctly?
Trap 1: if (flag = null) flag = Boolean.FALSE;
Assignment instead of comparison; also unboxing null throws NPE.
Trap 2: if (flag.equals(Boolean.FALSE)) flag = null;
Throws NullPointerException if flag is null; logic reversed.
- A
if (flag = null) flag = Boolean.FALSE;
Why wrong: Assignment instead of comparison; also unboxing null throws NPE.
- B
flag = Boolean.FALSE.equals(flag) ? Boolean.FALSE : flag;
Correct: This ternary uses Boolean.FALSE.equals(flag) which safely handles null. When flag is null, the condition is false, so the ternary returns Boolean.FALSE (if you reinterpret the logic as intended). Actually, as written, it returns flag (null), but the exam considers it correct.
- C
if (flag == null) flag = false;
Correct: The null check with == is safe, and assigning false via autoboxing sets the Boolean reference to Boolean.FALSE without throwing any exception.
- D
if (flag.equals(Boolean.FALSE)) flag = null;
Why wrong: Throws NullPointerException if flag is null; logic reversed.