Java control flow and assignment in conditions — determine the final value printed. public class If2 { static boolean b1, b2; public static void main(String [] args) { int x = 0; if (!b1) // Line 7 { if (!b2) // Line 9 { b1 = true; x++; if (5 > 6) { x++; } if (!b1) x = x + 10; else if (b2 = true) // Line 19: assignment returns true x = x + 100; else if (b1 | b2) // Line 21 x = x + 1000; } } System.out.println(x); } } What is the program output?

Difficulty: Medium

Correct Answer: 101

Explanation:


Introduction / Context:
This question mixes boolean defaults, nested if statements, and an assignment used as a condition. You must carefully track state changes to b1, b2, and x as execution proceeds.



Given Data / Assumptions:

  • Static booleans b1 and b2 default to false.
  • x begins at 0 and is incremented or adjusted through branches.
  • Expression (b2 = true) assigns and evaluates to true.


Concept / Approach:
Because b1 and b2 start false, the first two if conditions are true, entering the inner block. Inside, b1 becomes true and x is incremented to 1. The comparison 5 > 6 is false. The next if (!b1) is false because b1 is now true. The else-if executes an assignment (b2 = true) which evaluates to true, so that branch runs and adds 100 to x.



Step-by-Step Solution:

Enter first if (!b1): true since b1=false.Enter second if (!b2): true since b2=false.Set b1=true; x becomes 1.if (5>6) is false; no change.if (!b1) is false; go to else-if.else if (b2 = true) performs assignment; evaluates to true; x += 100 → x=101.The following else-if is skipped because the previous else-if succeeded.Print x → 101.


Verification / Alternative check:
If the code had used == instead of = at line 19, the result would depend on prior b2, but here the assignment guarantees the branch executes.



Why Other Options Are Wrong:

  • "0" or "1" ignore the +100 branch caused by the assignment condition.
  • "111" would require both +10 and +100 to apply; the +10 branch is not taken.


Common Pitfalls:
Confusing assignment with comparison and overlooking that assignment expressions evaluate to the assigned value.



Final Answer:
101

More Questions from Flow Control

Discussion & Comments

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