Switch case
In the if-else statement, as the number of alternatives increases,complexity of the program also increases.This not only makes the code difficult to read but also hard to debug.
Switch case statement is used to select and execute one statement from multiple statemens depending upon the condition.Switch statement tests the value of an expression against a list of given case values.When the value of expression matches with the case, the set of statements associated with that case is executed.
Syntax of Switch Case:
In the if-else statement, as the number of alternatives increases,complexity of the program also increases.This not only makes the code difficult to read but also hard to debug.
Switch case statement is used to select and execute one statement from multiple statemens depending upon the condition.Switch statement tests the value of an expression against a list of given case values.When the value of expression matches with the case, the set of statements associated with that case is executed.
Syntax of Switch Case:
1 2 3 4 5 6 7 8 9 10 11 12 | switch(expression) { case 1: //code to be executed for case 1 break; case 2: //code to be executed for case 2 break; ...... default: code to be executed if none of the cases are matched } |
Here the test expression can be an and algebraic expression,integer,character but not float and decimal values
Here's a question for you.What will be the output of the following code?
public class SwitchExample { public static void main(String[] args) { int n=20; switch(n){ case 10: System.out.println("10"); case 20: System.out.println("20"); case 30: System.out.println("30"); default:System.out.println("Not in 10, 20 or 30"); } } }
The output will be:
20
30
Not in 10, 20 or 30
Instead of expected output we got this..but why??
Because we forgot to write break statement in cases!! The break statement is used to jump out of the switch and loops.Java switch is a fall-through statement, it means once if finds the matching case it will keep on executing all the remaining cases(even the default case)until a break statement is encountered.So the correct code is:
public class SwitchExample { public static void main(String[] args) { int n=20; switch(n){ case 10: System.out.println("10");break; case 20: System.out.println("20");break; case 30: System.out.println("30");break; default:System.out.println("Not in 10, 20 or 30"); } } }
No comments:
Post a Comment