Switching on a Float wrapper reference in Java: determine what happens at compile time for the following. Float f = new Float("12"); switch (f) { case 12: System.out.println("Twelve"); case 0: System.out.println("Zero"); default: System.out.println("Default"); }
-
AZero
-
BTwelve
-
CDefault
-
DCompilation fails
-
ETwelve Zero Default
Answer
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:
fis aFloatobject.- Case labels are integer literals.
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