02.Java switch Statement
02.Java switch Statement
In this tutorial, you will learn to use the switch statement in Java to control the
flow of your program’s execution with the help of examples.
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
...
...
default:
// default statements
}
class Main {
public static void main(String[] args) {
case 29:
size = "Small";
break;
case 42:
size = "Medium";
break;
case 48:
size = "Extra Large";
break;
default:
size = "Unknown";
break;
}
System.out.println("Size: " + size);
}
}
Run Code
Output:
Size: Large
In the above example, we have used the switch statement to find the size.
Here, we have a variable number . The variable is compared with the value of
each case statement.
Since the value matches with 44, the code of case 44 is executed.
size = "Large";
break;
...
case 29:
size = "Small";
break;
...
int expression = 2;
// matching case
case 2:
System.out.println("Case 2");
case 3:
System.out.println("Case 3");
default:
System.out.println("Default case");
}
}
}
Run Code
Output
Case 2
Case 3
Default case
In the above example, expression matches with case 2 . Here, we haven't used
the break statement after each case.
Hence, all the cases after case 2 are also executed.
This is why the break statement is needed to terminate the switch-
case statement after the matching case. To learn more, visit Java break
Statement.
int expression = 9;
switch(expression) {
case 2:
System.out.println("Small Size");
break;
case 3:
System.out.println("Large Size");
break;
// default case
default:
System.out.println("Unknown Size");
}
}
}
Run Code
Output
Unknown Size