The switch Construct
The switch Construct
Another decision construct available in Java is switch construct.switch construct is used when there are multiple values of same varible are to be tested.The switch statement successively test the value of an expression or a variable against a list of inetger or character constants.Whenever a match is found the statement associated with that case constant are executed.Lets look at Syntax:-
switch(variable_name)
{
case expression1: statements;
case expression2: statements;
.
.
.
case expressionn: statements;
default: statements;
}
switch is a keyword which is followed by parentheses
switch(1)
the case keyword is followed by a constant like
case 1: x=y+z;
Note:There should be no difference in data types of case constants and switch variable.
Break statement:-
The break statements cause the program flow to exit from the current body of construct.Contol now passes to the very next statement followed by the end of switch construct.If break is not used then program flow would be linear and all case statements will execute despite any value or constants.
Consider following example:-
switch(n)
{
case 1: System.out.println("1");
case 2: System.out.println("2");
case 3: System.out.println("3");
case 4: System.out.println("4");
default: System.out.println("5");
}
In this case the output would be
1
2
3
4
5
Now consider the example:-
int n=1;
switch(n)
{
case 1: System.out.println("1");
break;
case 2: System.out.println("2");
break;
case 3: System.out.println("3");
break;
case 4: System.out.println("4");
break;
default: System.out.println("5");
}
In this case the output would be 1,because control jumps after case statement of value 1 executes thus not executing any other statements.
SCJP QUOTE:-Check for various tricky variations on switch construct.
The default keyword:-The statements associated with the default keyword are executed if the value of the switch variable does not match any of the case statements.
For Example:-
int n=4;
switch(n)
{
case 1: System.out.println("1");
break;
case 2: System.out.println("2");
break;
default:System.out.println("no match");
}
The output would be no match
IMPORTANT:-
1.The default label ,if used must be the last option in the switch construct.
2.It is not necessary to use default construct.
3.The case expression can be of either numeric or character data type.


















0 comments:
Post a Comment
Post a Comment