The Switch Statement
The switch statement like, "if/then/else" is used to test for conditions and execute code. However unlike "if/then/else", a "switch" can execute more than one code block. A switch is given a value which is tested against a case label. If the value evaluates to true then the code block for that case label will be executed. Case labels can be of several data types namely byte, short, char, and int primitive data types as well as strings, enums and a few other special classes.A switch statement also has a "default" case label which executes a code block when no other case label matches the condition. The code below demonstrates a simple "switch" statement.
- class Program {
- public static void main(String args[]){
- int userType = 2;
- switch (userType) {
- case 1:
- System.out.println("Hello admin");
- break;
- case 2:
- System.out.println("Hello supper admin");
- break;
- default:
- System.out.println("Who are you?");
- }
- }
- }
If a case label does not have a break statement, the "switch" statement will continue to execute label blocks regardless of the label expression until it either encounters a break statement or the "switch" statement has completed is execution flow.
The following code sample prints the number 3-6.
- class Program {
- public static void main(String args[]){
- int index = 3;
- switch (index){
- case 1:
- System.out.println("1");
- case 2:
- System.out.println("2");
- case 3:
- System.out.println("3");
- case 4:
- System.out.println("4");
- case 5:
- System.out.println("5");
- case 6:
- System.out.println("6");
- }
- }
- }
No comments:
Post a Comment