Switching on a Float wrapper reference in Java: determine what happens at compile time for the following.\n\nFloat f = new Float("12");\nswitch (f)\n{\n case 12: System.out.println("Twelve");\n case 0: System.out.println("Zero");\n default: System.out.println("Default");\n}

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.
  • 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

More Questions from Flow Control

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion