The switch statement tests the equality of a variable against multiple values.
- The case values must be unique.
- There can be n numbers of cases.
- The value must be literal or constant.
- The case value has a default label which is optional.
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
……
default:
//code to be executed if the cases are not matched
}
class Switch1 { public static void main(String args[]) { int a=2; switch(a) { case 1: System.out.println("Addition program is executed"); break; case 2: System.out.println("Subtraction program is executed"); break; case 3: System.out.println("Divide program is executed"); break; default: System.out.println("Wrong case pressed"); } } } Output: Subtraction program is executed