Control Flow · Lesson 28 of 150
switch
A switch statement checks a single value against multiple possible matching cases and runs the code block for whichever case matches. It's a cleaner alternative to writing many else if checks for a single variable.
01What is a switch Statement?
A switch statement checks a single value against multiple possible matching cases and runs the code block for whichever case matches. It's a cleaner alternative to writing many else if checks for a single variable.
02Why is it used?
When a program needs to compare one variable against many fixed possibilities — like a day number, a menu choice, or a grade letter — switch makes the code more organized and often easier to read than a long else-if chain.
03Real-Life Example
Think of a TV remote's channel selector. Based on the exact channel number pressed, the TV switches to that specific channel. Each channel number is like a case, matched exactly against your input.
04Syntax
javaswitch (variable) { case value1: // code break; case value2: // code break; default: // code if nothing matches }
05Example Program
javapublic class SwitchDemo { public static void main(String[] args) { int day = 3; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; default: System.out.println("Invalid day"); } } }
Output:
Wednesday