Java boolean assignments in if/else chain — what character is printed? boolean bool = true; if (bool = false) { // Line 2: assignment, not comparison System.out.println("a"); } else if (bool) { System.out.println("b"); } else if (!bool) { System.out.println("c"); // Line 12 } else { System.out.println("d"); } Choose the exact output.
-
Aa
-
Bb
-
Cc
-
Dd
Answer
Correct Answer: c
Explanation
Introduction / Context:This classic trap distinguishes assignment (=) from comparison (==) inside an if condition. The code assigns false to the variable and then evaluates the new value in the control flow.
Given Data / Assumptions:
- Initial: bool is true.
- The first if uses assignment: bool = false.
- Subsequent else-if conditions depend on the updated value of bool.
Concept / Approach:In Java, an assignment expression has the value of the assigned result. Thus if (bool = false) assigns false and then tests false, so the first branch does not execute. The chain continues with the updated bool value.
Step-by-Step Solution:
Evaluate if (bool = false) → bool becomes false, condition is false → skip "a".Evaluate else if (bool) → bool is false → skip "b".Evaluate else if (!bool) → !false is true → execute and print "c".The final else is not reached.Verification / Alternative check:Change the first line to if (bool == false) (comparison) and the flow changes. Or write if (!bool) for clarity.
Why Other Options Are Wrong:
- "a" would require the first condition to be true; it is forced false by assignment.
- "b" requires bool to be true; it is explicitly set to false.
- "d" is never reached because the preceding else-if evaluates to true.
Common Pitfalls:Using assignment in conditions unintentionally; always enable compiler warnings or code style checks to prevent this.
Final Answer:c