Difficulty: Easy
Correct Answer: Compilation fails.
Explanation:
Introduction / Context:
This checks whether you can distinguish assignment from comparison in Java conditions. Unlike some languages, Java requires a boolean expression inside if
. Assigning an int
inside the condition is not allowed.
Given Data / Assumptions:
x = 3
, y = 1
.x = y
(assignment) instead of x == y
(equality comparison).
Concept / Approach:
The assignment expression x = y
yields an int
value, not a boolean
. Java will not convert non-zero integers to true
automatically; thus the compiler reports “incompatible types: int cannot be converted to boolean”.
Step-by-Step Solution:
Compilation: the parser accepts the syntax, but type checking fails.Error message: assignment returns int
; if
expects boolean
.No runtime output is possible.
Verification / Alternative check:
Change to if (x == y)
and the code will compile and run. Alternatively, explicitly test a boolean condition, e.g., if ((x = y) == 1)
(though that is poor style).
Why Other Options Are Wrong:
They assume execution proceeds; it cannot due to the type error.
Common Pitfalls:
Accidentally writing =
instead of ==
; always enable compiler warnings or use linters/IDE inspections.
Final Answer:
Compilation fails.
Discussion & Comments