Java programming — Type compatibility in assignments inside boolean expressions: class Equals { public static void main(String [] args) { int x = 100; double y = 100.1; boolean b = (x = y); // Line 7 System.out.println(b); } }
Correct Answer: Compilation fails
Introduction / Context:This tests Java's strict type system for assignments and the difference between assignment (=) and comparison (==) within expressions.
Given Data / Assumptions:
- x is an int; y is a double.
- The code attempts to assign y to x within a boolean context.
Concept / Approach:In Java, assigning a double to an int without an explicit cast is a compile-time error (possible lossy conversion). Also, (x = y) would have type int (the left-hand type) if it were legal, which is not boolean.
Step-by-Step Solution:
Check type compatibility: x = y requires narrowing conversion from double to int; without a cast, it fails to compile.Even with an explicit cast, the expression would not be boolean and still could not be assigned to boolean b without comparison.Verification / Alternative check:Replace with boolean b = (x == y); or with a cast and comparison to observe correct usage.
Why Other Options Are Wrong:They assume the code runs and produces true/false or an exception; the compiler prevents execution.
Common Pitfalls:Accidentally using = instead of ==, and forgetting Java does not allow implicit narrowing conversions from double to int.
Final Answer:Compilation fails