Java Switch Statement
In Java, the switch statement is used to execute one of several code blocks based on the value of a variable or expression. The syntax of the switch statement is as follows:
switch (expression) {
case value1:
// code block to be executed if expression equals value1
break;
case value2:
// code block to be executed if expression equals value2
break;
.
.
.
case valueN:
// code block to be executed if expression equals valueN
break;
default:
// code block to be executed if expression does not equal any of the values
}
Here, the expression
is the variable or expression whose value is being compared, and each case
label represents a value that the expression might equal. If the expression matches one of the values, the corresponding code block is executed. If none of the cases match, the code in the default
block is executed.
The break
statement is used to exit the switch statement after a code block has been executed. If the break
statement is not used, the code will continue to execute until it reaches the end of the switch block or a break
statement is encountered.
Here's an example of how the switch statement can be used in Java:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number (1-3): ");
int number = input.nextInt();
switch (number) {
case 1:
System.out.println("You entered one.");
break;
case 2:
System.out.println("You entered two.");
break;
case 3:
System.out.println("You entered three.");
break;
default:
System.out.println("Invalid number.");
break;
}
}
}
In this example, the day
variable is compared to the values in the switch statement, and the corresponding dayName
string is assigned. Since day
is equal to 3, the code block for case 3
is executed and the dayName
variable is assigned the value "Wednesday". The break
statement is used to exit the switch statement and prevent execution of the other code blocks. Finally, the value of dayName
is printed to the console