المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : switch Statement in Java



A7med Baraka
11-02-2008, 03:19 AM
switch Statement in Java



Syntax example







switch (expr) {
case c1:
statements // do these if expr == c1
break;
case c2:
statements // do these if expr == c2
break;
case c2:
case c3:
case c4: // Cases can simply fall thru.
statements // do these if expr == any of c's
break;
. . .
default:
statements // do these if expr != any above
}



Switch keywords

switchThe switch keyword is followed by a parenthesized integer expression, which is followed by the cases, all enclosed in braces.. The switch statement executes the case corresponding to the value of the expression. Normally the code in a case clause ends with a break statement, which exits the switch statement and continues with the statement following the switch. If there is no corresponding case value, the default clause is executed. If no case matched and there is no default clause, execution continues after the end of the switch statement.caseThe case keyword is followed by an integer constant and a colon. This begins the statements that are executed when the switch expression has that case value. defaultIf no case value matches the switch expression value, execution continues at the default clause. This is the *****alent of the "else" for the switch statement. It is written after the last case be convention, and typically isn't followed by break because execution just continues out the bottom of switch if this is the last clause. breakThe break statement causes execution to exit to the statement after the end of the switch. If there is no break, execution flows thru into the next case. Flowing directly into the next case is almost always an error.
Example - Random comment




String comment; // The generated insult.
int which = (int)(Math.random() * 3); // Result is 0, 1, or 2.

switch (which) {
case 0: comment = "You look so much better than usual.";
break;
case 1: comment = "Your work is up to its usual standards.";
break;
case 2: comment = "You're quite competent for so little experience.";
break;
default: comment = "Oops -- something is wrong with this code.";
}



*****alent if statement

A switch statement can often be rewritten as an if statement in a straightforward manner. For example, the preceding switch statement could be written as follows. When one of a number of blocks of code is selected based on a single value, the switch statement is generally easier to read. The choice of if or switch should be based on which is more readable.


String comment; // The generated insult.
int which = (int)(Math.random() * 3); // Result is 0, 1, or 2.

if (which == 0) {
comment = "You look so much better than usual.";
} else if (which == 1) {
comment = "Your work is up to its usual standards.";
} else if (which == 2) {
comment = "You're quite competent for so little experience.";
} else {
comment = "Oops -- something is wrong with this code.";
}