Multiple choice technology programming languages

What gets printed after this boolean b = false; if (b = true){ System.out.println("True"); }

  1. Prints "True"

  2. Prints nothing

  3. Prints false

  4. Error in if condition

Reveal answer Fill a bubble to check yourself
A Correct answer
Explanation

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.

AI explanation

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 (==).