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
bis created and set tofalse.
2. The Loop Condition (b = !b)
This is the tricky part.
for(int i = 0; b = !b; )
Initialization:
int i = 0runs once at the start.Condition:
b = !bacts as the loop condition.Crucial Concept: In Java, an assignment (like
x = y) returns the new value of the variable.First Check:
bisfalse.!bistrue. So,bbecomestrue. The expression evaluates totrue, so the loop enters.Second Check:
bis nowtrue.!bisfalse. So,bbecomesfalse. The expression evaluates tofalse, so the loop stops.
- Note:
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 toiafter the value is used/printed. So,ibecomes 1, but only0appears 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).