PREV NEXT
Java Switch Statement can have multiple execution paths. It is similar to that of ‘if else-if’ statement except that switch can handle expressions which results to any primitive data type and if statements handle only boolean expressions.
Syntax for java Switch Statement:
switch (expression)
{ case ‘value1’: //statements break; case ‘value2’: //statements break; case ‘value3’: //statements break; … default: //statements } |
- The value of the expression is matched with the case values. Only the statements inside the matched case are executed.
- The ‘break’ keyword is added after each case in order to exit from the switch case. If the ‘break’ keyword is not specified, all the cases would be checked and the matching cases would be executed.
- The default case is considered when no case value is matched.
Example for java Switch Statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
Class Number{ Public static void main(String args[]){ int n =2; switch (n) {case 1: System.out.println(“One”); break; case 2: System.out.println(“Two”); break; case 3: System.out.println(“Three”); break; case 4: System.out.println(“Four”); break; case 5: System.out.println(“Five”); break; Default: System.out.println(“Enter a number within 1 to 5”); } } |
Output:
Two |
In the above program the value of n decides which statement to be executed. Here it is 2 and hence the statement inside the case 2 is executed.