switch statement
switch statement
Syntax
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Program
public class switch_example
{
public static void main(String args[])
{
int age = 20;
switch(age)
{
case 10:
System.out.println("You are child.");
break;
case 20:
System.out.println("You are teenager.");
break;
case 30:
System.out.println("You are matured.");
break;
case 40:
System.out.println("You are old.");
break;
default:
System.out.println("You are ageless.");
}
}
}
Output
You are teenager.
Explanation
The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Basically, the expression can be byte, short, char, and int primitive data types. Beginning with JDK7, it also works with enumerated types ( Enums in java), the String class and Wrapper classes.
Some Important rules for switch statements :
- Duplicate case values are not allowed.
- The value for a case must be the same data type as the variable in the switch.
- The value for a case must be a constant or a literal.Variables are not allowed.
- The break statement is used inside the switch to terminate a statement sequence.
- The break statement is optional. If omitted, execution will continue on into the next case.
- The default statement is optional, and it must appear at the end of the switch.
We will see break and continue keyword in other lesson.
Comments
Post a Comment