If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Java, the switch
statement provides an alternative way to make decisions based on the value of an expression. It allows you to test the value of a variable against a list of constant values and execute different blocks of code based on the matching value. The switch
statement is often used as an alternative to long chains of if-else
statements when comparing multiple constant values.
The basic syntax of the switch
statement is as follows:
javaCopy code
switch (expression) {
case value1:
// Code to be executed if expression equals value1
break;
case value2:
// Code to be executed if expression equals value2
break;
// Additional cases as needed...
default:
// Code to be executed if none of the cases match the expression
}
Here's an example Java program demonstrating the usage of the switch
statement:
javaCopy code
import java.util.Scanner;
public class SwitchExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a day number (1-7): ");
int dayNumber = scanner.nextInt();
// Use switch to display the day of the week based on the day number
String dayName;
switch (dayNumber) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
case 4:
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
break;
case 6:
dayName = "Friday";
break;
case 7:
dayName = "Saturday";
break;
default:
dayName = "Invalid day number";
}
System.out.println("The day of the week is: " + dayName);
scanner.close();
}
}
Example output:
mathematicaCopy code
Enter a day number (1-7): 3
The day of the week is: Tuesday
In the example above, the program prompts the user to enter a day number (1-7). The switch
statement then compares the dayNumber
variable against different cases (values 1 to 7) and sets the dayName
variable accordingly. If dayNumber
matches any of the cases, the corresponding day name is assigned to dayName
. If none of the cases match, the default
case is executed, and "Invalid day number" is assigned to dayName
.
The break
statement is essential inside each case to exit the switch block once a matching case is found. Otherwise, the code will fall through to the subsequent cases, and all matching cases will be executed, which is usually not the desired behavior.
The switch
statement is particularly useful when you have multiple fixed values to compare against a single variable, making the code cleaner and more concise compared to using multiple if-else
statements.
Comments: 0