Summary: In this tutorial, you will learn about the switch statement in Java with the help of examples.
Switch Statement in Java
In Java, the switch
statement is a control flow statement that allows a program to execute a block of code among several choices.
It provides an easy way to dispatch execution to different parts of code based on the value of an expression.
The syntax of the switch
statement in Java is as follows:
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
...
default:
// code block
}
The switch
statement starts with the switch
keyword, followed by an expression in parentheses. The expression can be of any type that can be converted to an int
value, such as char
, byte
, short
, or int
.
The switch
statement is followed by one or more case
labels, each of which is associated with a value. The case
labels are followed by a colon (:) and a block of code to be executed if the value of the expression matches the value of the case
label.
break and default in Switch
The default
label is optional and is used to specify a block of code to be executed if the value of the expression does not match any of the values specified in the case
labels.
It’s important to note that the break
statement is used to exit the switch
statement and prevent the execution of the subsequent code.
If the break
statement is omitted, the code execution will continue to the next case
label and execute all the code associated with it, even if the value of the expression does not match. This can be useful in some cases, but it’s important to use it with caution to avoid unintended behavior.
Example using Switch Statement in Java
Here is an example of a switch
statement in Java:
char grade = 'B';
switch (grade) {
case 'A':
System.out.println("Excellent");
break;
case 'B':
System.out.println("Good");
break;
case 'C':
System.out.println("Average");
break;
case 'D':
System.out.println("Poor");
break;
case 'F':
System.out.println("Fail");
break;
default:
System.out.println("Invalid grade");
}
// Output: Good
In this example, the switch
statement compares the value of the grade
variable (which is 'B'
) with the values specified in each case
label.
The code associated with the case 'B':
label is executed, which prints “Good” to the console.
Example 2:
int month = 2;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
System.out.println("31 days");
break;
case 4:
case 6:
case 9:
case 11:
System.out.println("30 days");
break;
case 2:
System.out.println("28 or 29 days");
break;
default:
System.out.println("Invalid month");
}
// Output: 28 or 29 days
In this example, the switch
statement compares the value of the month
variable (which is 2
) with the values specified in each case
label.
The code associated with the case 2:
label is executed, which prints “28 or 29 days” to the console.