Switch Case Statement Syntaxes and Example in Java
The switch case statement in Java is a multi-way branch statement. If the switch statement evaluates its expression, then executes all statements that follow the matching case label. If there are several possible outcomes or values depending on that you want to execute statements then you must choose switch case block.
Syntax:
switch(expression)
{
case 1: action 1;
case 2: action 2;
...
case n: action n;
default: default action;
}
Switch Case Rules in Java
- There is no limit on the number of cases inside a switch block in java.
- The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal.
- In Java SE 7 and later, you can use a String object in the switch statement's expression.
- The value for a case must not be variables.
- Duplicate case values are not allowed.
- Technically, the final break is not required because flow falls out of the switch statement.
- Each break statement terminates the enclosing switch statement.
- The default section handles all values that are not explicitly handled by one of the case sections.
- The default statement is optional, and it must appear at the end of the switch.
- The statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
What is fall through in switch case in Java?
All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered. The fall through means the flow of control will fall from a matched case to the end of switch or until encounter a break statement.
Example: Consider you have a switch with integer value and 3 cases with 1,2 and 3 value. If case 2 is matched then case 2 and subsequent cases will get executed.
int i=2;
switch(i)
{
case 1: System.out.println("Case 1");
case 2: System.out.println("Case 2");
case 3: System.out.println("Case 3");
}
Output:-
Case 1
Case 2
Example: Perform arithmetic oprations.
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System. in);
System.out.println("***Choose an Operation***\n + Addtion \n - Subtraction \n / Division \n * Multiplication");
char op = sc.next().charAt(0);
System.out.println("Enter 2 numbers");
int a = sc.nextInt();
int b = sc.nextInt();
switch(op)
{
case '+': System.out.println("Sum is "+(a+b));break;
case '-': System.out.println("Sub is "+(a-b));break;
case '/': System.out.println("Div is "+(a/b));break;
case '*': System.out.println("Mul is "+(a*b));break;
default : System.out.println("Invalid opration selected");
}
}
}