Predict output of the following if the value of n is (a)2 (b)4 [2]
switch(n)
{
case 1 : System.out.println(“New York”);
case 2 : System.out.println(“Boston”);
break;
case 3 : System.out.println(“Alaska”);
break;
case 4 : System.out.println(“California”);
case 5 : System.out.println(“Chicago”);
default : System.out.println(“Wrong Choice”);}
Answers
Answer:
a)When the value of n is 2...
Output:-
Boston
Explaination:-
If the value of n is 2 then the control will check if any case code is matching with switch value..if yes,it will execute that statement. In the given code above, case 2 is matching with switch value (switch (n)where n is 2) so, the control will execute the statement of case 2 and print "Boston".
Note:- There is a break statement after case 2 so the control will directly come out from the switch block.
---------------------------------------
b)When value of n is 4....
Output:-
California
Chicago
Wrong Choice
Explaination:-
If the value of n is 4 then the control will check if any case code is matching with switch value..if yes,it will execute that statement. In the given code above, case 4 is matching with switch value (switch (n)where n is 4) so, the control will execute the statement of case 4 and print "California".
Note:- There is no break statement after case 4 it will result in fall-through.
•What is fall through?
When there is no break statement, the control will execute more than 1 case statement even if they are false.
Given code above...after case 4 there is no break statement, so the control will execute case 5,6 and the default statement
That's why , the output is ....
California
Chicago
Wrong Choice