Simple Java loop code that can be easily confused!

public class MainClass {
  public static void main(String[] args) {
    boolean b = false;
    for(int i = 0; b = !b; ) {
      System.out.println(i++);
      }
  }
}

Output

0

Detailed Breakdown

Here is what is happening step-by-step:

1. The Setup

​​boolean b = false;
  • A boolean variable b is created and set to false.

2. The Loop Condition (b = !b)

This is the tricky part.

for(int i = 0; b = !b; )
  • Initialization: int i = 0 runs once at the start.

  • Condition: b = !b acts as the loop condition.

    • Crucial Concept: In Java, an assignment (like x = y) returns the new value of the variable.

    • First Check: b is false. !b is true. So, b becomes true. The expression evaluates to true, so the loop enters.

    • Second Check: b is now true. !b is false. So, b becomes false. The expression evaluates to false, so the loop stops.

  • Note: 
  • The condition section in a Java loop is a Boolean expression that determines whether the loop should continue executing or terminate. The loop runs as long as the condition evaluates to true, and stops when it becomes false.​


3. Inside the Loop

​System.out.println(i++);

  • Print: It prints the current value of i, which is 0.

  • Increment: The ++ is a post-increment operator. It adds 1 to i after the value is used/printed. So, i becomes 1, but only 0 appears on the screen.

Execution Trace Table

Step
Value of i
Value of b
Loop Condition (b = !b)
Action
Start
0
false
-
-
Iter 1
0
false true
True (Loop runs)
Print 0. i becomes 1.
Iter 2
1
true false
False (Loop stops)
Exit loop.

Summary

The code effectively toggles the boolean switch on (allowing entry), executes the body once, and then toggles the switch off (preventing re-entry).

← Back to Learning Journey