Java Programming - Flow Control - Discussion

Discussion :: Flow Control - Finding the output (Q.No.13)

13. 

What will be the output of the program?

Float f = new Float("12"); 
switch (f) 
{
    case 12: System.out.println("Twelve"); 
    case 0: System.out.println("Zero"); 
    default: System.out.println("Default"); 
}

[A]. Zero
[B]. Twelve
[C]. Default
[D]. Compilation fails

Answer: Option D

Explanation:

The switch statement can only be supported by integers or variables more "narrow" than an integer i.e. byte, char, short. Here a Float wrapper object is used and so the compilation fails.


Mayur said: (Dec 16, 2012)  
Float f = new Float("12"); is this vaild?

Neva said: (Feb 20, 2013)  
Switch Statement allows "String" since Java 7. :)

Moni said: (Jul 30, 2014)  
Switch statement can take Wrapper object also,but compilation fails because of Float Wrapper class.

We can't take Float, Double Wrapper classes like float primitive data type float double.

Praveen Ps said: (Oct 12, 2014)  
From java 7 onward we can use string inside switch.

Mitul said: (Oct 9, 2015)  
Argument of float is string & value provided by switch is integer. That's why it is throwing error. Please correct me if I understood wrongly.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.