Java – Switch Selection Statement

Home/Java - Tutorial/Java - Control Statements/Java – Switch Selection Statement
Java – Switch Selection Statement 2017-06-13T10:06:05+00:00

switch :

The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression.
It is difficult to understand large number of if else..if statements. So we have switch statement.
Syntax :
switch (expression)
{
case value 1 :
statement 1 ; break;
case value 2 :
statement 2 ; break;
case value N :
statement N ; break;
default :
statements ; break;
}
The expression must be of type byte, short, int, or char; each of the values specified in the case statements must be of a type compatible with the expression.
Each case value must be a unique literal (constant, not a variable). Duplicate case values are not allowed.
The value of the expression is compared with each ‘case’ values. If a match is found, the corresponding statement or statements are executed.
If no match is found, statement or statements in the default case are executed. Default statement is optional.
If default statement is absent, then if no matches are found, then the switch statement completes without doing anything.
The break statement is used inside the switch to terminate a statement sequence.
NOTE : We will study break statement in further chapter.
Ex.

 


Output :
 
Enter a : 5
Enter b : 6
Enter 1 for addition
Enter 2 for subtraction
Enter 3 for multiplication
Enter 4 for division
Enter your choice : 3
a * b = 30.0

Prev Next