Core Java Fundamentals ยท Conditional Statements
Learn how to use the switch statement to control the flow of execution based on the value of a variable or expression.
public class SwitchDemo {
public static void main(String[] args) {
int day = 4; // Let's check the 4th day of the week
String dayString;
switch (day) {
case 1:
dayString = "Monday";
break;
case 2:
dayString = "Tuesday";
break;
case 3:
dayString = "Wednesday";
break;
case 4:
dayString = "Thursday";
break;
case 5:
dayString = "Friday";
break;
case 6:
dayString = "Saturday";
break;
case 7:
dayString = "Sunday";
break;
default:
dayString = "Invalid day";
break;
}
System.out.println("The day is: " + dayString);
}
}day and initialize it with the value 4.dayString. It is not yet initialized, so it holds a null value.switch statement. It evaluates the expression inside the parentheses, which is the variable day. The value is 4.case label that matches the value 4. It skips cases 1, 2, and 3 and finds a match at case 4.case 4 is executed. The string "Thursday" is assigned to the dayString variable.break statement is executed. This immediately terminates the switch block, and the program continues execution after the switch.dayString to the console.