Case label variations
Case label and switch arguments can be a constant expression. The switch argument can be a variable expression.
Example:
Using variable switch arguement.
import java.io.*;
class GFG {
public static void main(String[] args)
{
int x = 2;
switch (x + 1) {
case 1:
System.out.println(1);
break;
case 1 + 1:
System.out.println(2);
break;
case 2 + 1:
System.out.println(3);
break;
default:
System.out.println("Default");
}
}
}
Output
3
A case label cannot be a variable or variable expression. It must be a constant expression.
import java.io.*;
class GFG {
public static void main(String[] args)
{
int x = 2;
int y = 1;
switch (x) {
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
break;
case x + y:
System.out.println(3);
break;
default:
System.out.println("Default");
}
}
}
./GFG.java:16: error: constant expression required
case x+y:
^
1 error
Switch Statements in Java
The switch statement in Java is a multi-way branch statement. In simple words, the Java switch statement executes one statement from multiple conditions.
It is like an if-else-if ladder statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. The expression can be a byte, short, char, or int primitive data type. It tests the equality of variables against multiple values.