Java boolean assignments in if/else chain — what character is printed?\n\nboolean bool = true;\nif (bool = false) { // Line 2: assignment, not comparison\n System.out.println("a");\n}\nelse if (bool) {\n System.out.println("b");\n}\nelse if (!bool) {\n System.out.println("c"); // Line 12\n}\nelse {\n System.out.println("d");\n}\n\nChoose the exact output.

Difficulty: Easy

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

More Questions from Flow Control

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion