Click to enter _ more _java thousand ask
How switch usesThe switch allows you to perform different code for the value of a variable.
The switch statement is similar to the IF Else statement, which can be implemented by the if else completely, with the difference being that the switch logic is clearer. If else details see here: how if Else uses
Syntax:
switch (expression) {case value://statementsbreak;//optionalcase value://statementsbreak;//optional//you can has any Number of case Statements.default://optional//statements}
The following rules apply to the switch statement:
1. The expression used in the switch statement can only be one byte , Short,int and or char,enum itself is an int, so it can also be used.
2. Switch can have any number of case statements. Each case is followed by a comparison of the value and ":".
3. The value following the case must be the same as the expression type and must be a constant .
4. When the value following the case is equal to expression, the code snippet corresponding to the case is executed until the break statement is reached.
5, go straight to the break statement, jump directly out of switch, execute subsequent code.
6, not every case must have a break. If there is no break, the code snippet corresponding to the next case will continue until the break is reached.
7. The switch statement can have a defaultcase, which must appear after all the. By default, no case is true when the default corresponding code snippet is executed.
Example:
public class Test {public static void main (String args[]) {//char grade = Args[0].charat (0); char grade = ' B '; switch (grade) { Case ' A ': System.out.println ("excellent!"); Break;case ' B ': Case ' C ': System.out.println ("Well Done"), Break;case ' D ': System.out.println ("You passed"), Case ' F ': System.out.println ("Better try Again"); Break;default:system.out.println ("Invalid grade");} System.out.println ("Your grade is" + grade);}}
Compile and run the program using the various command-line arguments above. This will produce the following results:
Well done
Your grade is a B
Click to enter Ooppookid's blog
Java technology _java Q (0018) _switch How to use