Difficulty: Easy
Correct Answer: Compilation fails
Explanation:
Introduction / Context:
This question tests which types are permitted in a Java switch
expression. Historically, Java allowed integral types (byte
, short
, char
, int
and their compatible enums), and since Java 7, String
. Floating-point types and their wrappers are not permitted.
Given Data / Assumptions:
f
is a Float
object.
Concept / Approach:
The switch
expression type must be compatible with case labels. A Float
(or float
) is invalid as a switch
discriminator. This causes a compile-time error before any execution.
Step-by-Step Solution:
Evaluate the switch expression type: Float
⇒ invalid for switch
.The compiler rejects the construct regardless of case labels.Therefore no output is produced at runtime.
Verification / Alternative check:
Change the code to int f = 12;
and the switch will compile and run, printing based on fall-through unless you insert break
.
Why Other Options Are Wrong:
They assume execution completes. The code never runs because of the invalid switch type.
Common Pitfalls:
Assuming boxed numeric types other than those compatible with integral switch semantics are allowed; Float
and Double
are not.
Final Answer:
Compilation fails
Discussion & Comments