What gets printed after this boolean b = false; if (b = true){ System.out.println("True"); }
-
Prints "True"
-
Prints nothing
-
Prints false
-
Error in if condition
The code uses assignment (=) instead of equality (==) in the if condition, so b becomes true and the condition passes. This is a common bug - the if statement evaluates the result of the assignment, which is the assigned value (true), causing 'True' to be printed.
In Java, an if-condition must be an expression of type boolean (unlike C, where any integer works). Here, b = true is an assignment expression whose value is the assigned value, true, and since b is declared as boolean, this assignment expression itself has type boolean — so it's a perfectly legal if-condition (it compiles, unlike if (someInt = 5) would, since int isn't boolean). The condition evaluates to true, so "True" is printed. This is a classic gotcha testing whether you know Java permits assignment-as-condition when the variable's type matches boolean, distinguishing it from an equality check (==).