switch Structures
The second selection structure in Java does not require the evaluation of a logical expression. It is called the switch Structure and gives the computer the power to choose from many alternatives. The switch statement has the following syntax:
switch(expression)
{
case value1: statements1
break;
case value2: statements2
break;
…
case valuen; statementsn
break;
default: statements
}
The expression (sometimes called the selector) is evaluated first and the value of the expression is then used to perform the actions specified in the statements that follow the reserved word case.
The expression is usually an identifier and the value is always an integral. The value of the expression determines which statement is selected for execution, therefore a particular case values must be unique.
One or more statements may follow a case symbol, and curly braces are unnecessary to group them.
The break statement may or may not appear after each statement.
A switch statement executes according to the following rules:
- When the value of the expression is matched against a case value (also called a label), the statements execute until either a break statement is found or the end of the switch structure is reached.
- If the value of the expression does not match any of the case values, the statements following the default label execute. If the switch structure has no default label, and if the value of the expression does not match any of the case values, the entire switch statement is skipped.
- A break statement causes an immediate exit from the switch structure.
Choosing Between an if...else and a switch Structure
No fixed rules exist that can be applied to decide whether to use an if...else structure or a switch structure to implement multiple selections, but you should remember the following considerations:
If multiple selections involve a range of values, you should use either an if...else structure or a switch structure, wherein you convert each range to a finite set of values.
If the range of values is infinite and you cannot reduce them to a set containing a finite number of values, you must use the if...else structure.
Call me and you will get the knowledge and skills you need instantly.
For inquiries contact me on my mobile number or email me at inquiry@eglobiotraining.com. View my multiply site http://erwinglobio.multiply.com
Prof. Erwin M. Globio, MSIT
Senior IT Lecturer
Far Eastern University
Email Address: inquiry@eglobiotraining.com
Skype: erwinglobio
Call Now:
SMART: 09393741359
SUN: 09323956678
No comments:
Post a Comment