Module 3 - Lesson 10

Switch Statements: Elegant Multi-Way Decisions

If-else-if အစား switch သုံးရင် code က ပိო clean ဖြစ်တယ်၊ ပိုဖတ်လွယ်တယ်။ Multiple cases တွေကို efficiently handle လုပ်နည်းကို လေ့လာကြမယ်။

⏱️ 40 minutes 📚 Intermediate 💻 Practical Examples

🎯 သင် သင်ယူမည့် အရာများ

ဒီ lesson မှာ သင် သင်ယူမည့် အရာများ:

  • Switch statement ရဲ့ syntax နဲ့ အလုပ်လုပ်ပုံ
  • Case labels နဲ့ break statement အသုံးပြုနည်း
  • Default case ကို ဘယ်လို သုံးရမလဲ
  • Switch vs If-Else-If - ဘယ်အချိန် ဘာသုံးရမလဲ
  • Fall-through behavior နဲ့ ဂရုစိုက်ရမည့် အချက်များ
  • Modern Java Switch expressions (Java 12+)
  • Real-world examples များ

📖 Switch Statement ဆိုတာ ဘာလဲ?

Switch statement ဆိုတာ variable တစ်ခုရဲ့ value ကို multiple possible values တွေနဲ့ နှိုင်းယှဉ်ပြီး matching case ကို execute လုပ်တဲ့ control flow statement ပါ။ If-else-if ladder ထက် code က ပို clean ဖြစ်ပြီး၊ ပိုမြန်ပါတယ်။

နေ့စဉ်ဘဝမှာ ဥပမာ:

  • Menu မှာ 1 နှိပ်ရင် → Coca Cola, 2 နှိပ်ရင် → Pepsi, 3 နှိပ်ရင် → Sprite
  • နေ့ရက် စစ်ဆေးခြင်း: Monday → အလုပ်နေ့, Saturday → စနေ, Sunday → တနင်္ဂနွေ
  • Grade စစ်ဆေးခြင်း: A → Excellent, B → Good, C → Average

If-else-if နဲ့ ရေးရင် ရှည်လျားမယ်၊ switch နဲ့ ရေးရင် ရှင်းလင်းမယ်!

If-Else-If vs Switch

အတူတူ ရလဒ် ထွက်ပေမယ့် switch က ပို clean:

If-Else-If (Verbose)
if (day == 1) {
    System.out.println("Monday");
} else if (day == 2) {
    System.out.println("Tuesday");
} else if (day == 3) {
    System.out.println("Wednesday");
} else if (day == 4) {
    System.out.println("Thursday");
} else if (day == 5) {
    System.out.println("Friday");
} else {
    System.out.println("Weekend");
}
Switch (Clean & Clear)
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    case 4:
        System.out.println("Thursday");
        break;
    case 5:
        System.out.println("Friday");
        break;
    default:
        System.out.println("Weekend");
}

🔹 Switch Statement Syntax

Basic syntax structure:

Java
switch (expression) {
    case value1:
        // value1 နဲ့ တူရင် execute
        statements;
        break;
    
    case value2:
        // value2 နဲ့ တူရင် execute
        statements;
        break;
    
    case value3:
        // value3 နဲ့ တူရင် execute
        statements;
        break;
    
    default:
        // ဘယ် case နဲ့မှ မတူရင် execute (optional)
        statements;
}

အရေးကြီးတဲ့ အချက်များ:

  • Expression: int, byte, short, char, String, enum ပဲ သုံးလို့ရတယ် (long, float, double မရဘူး)
  • Case values: Constant ဖြစ်ရမယ် (variables မသုံးနိုင်ဘူး)
  • break: Case ပြီးရင် switch ကနေ ထွက်ဖို့ (မပါရင် fall-through ဖြစ်တယ်)
  • default: Optional ပါ၊ ဘယ် case နဲ့မှ မကိုက်ရင် execute လုပ်တယ်

🔹 Simple Example: Day of Week

နံပါတ်ကနေ နေ့ရက် ထုတ်ပြခြင်း:

Java
public class DayOfWeek {
    public static void main(String[] args) {
        int dayNumber = 3;
        String dayName;
        
        switch (dayNumber) {
            case 1:
                dayName = "Monday";
                break;
            case 2:
                dayName = "Tuesday";
                break;
            case 3:
                dayName = "Wednesday";
                break;
            case 4:
                dayName = "Thursday";
                break;
            case 5:
                dayName = "Friday";
                break;
            case 6:
                dayName = "Saturday";
                break;
            case 7:
                dayName = "Sunday";
                break;
            default:
                dayName = "Invalid day";
        }
        
        System.out.println("Day " + dayNumber + " is " + dayName);
    }
}
Output:
Day 3 is Wednesday

🔹 Break Statement - အရေးကြီးဆုံး!

Break statement က case တစ်ခု execute ပြီးရင် switch ကနေ ထွက်ဖို့ သုံးတယ်။ break မပါရင် fall-through ဖြစ်ပြီး အောက်က cases တွေ ဆက် execute လုပ်တယ်!

Without Break (Fall-Through Bug!)

Java - WRONG!
int grade = 2;

switch (grade) {
    case 1:
        System.out.println("Excellent!");
        // break ပါရမယ်!
    case 2:
        System.out.println("Good!");
        // break ပါရမယ်!
    case 3:
        System.out.println("Average");
        // break ပါရမယ်!
    default:
        System.out.println("Need improvement");
}
Wrong Output (Fall-through!):
Good!
Average
Need improvement

⚠️ case 2 ပြီးတာနဲ့ မရပ်ဘဲ အောက်တွေ ဆက်လုပ်သွားတယ်!

With Break (Correct!)

Java - CORRECT!
int grade = 2;

switch (grade) {
    case 1:
        System.out.println("Excellent!");
        break;  // ✓
    case 2:
        System.out.println("Good!");
        break;  // ✓
    case 3:
        System.out.println("Average");
        break;  // ✓
    default:
        System.out.println("Need improvement");
}
Correct Output:
Good!

✓ case 2 execute ပြီး break နဲ့ ထွက်သွားတယ်

🔹 Intentional Fall-Through (တမင် ဆက်လုပ်စေခြင်း)

တခါတရံ fall-through က useful ဖြစ်နိုင်တယ် - multiple cases အတွက် တူညီတဲ့ code run ချင်ရင်:

Java
public class WorkingDay {
    public static void main(String[] args) {
        int day = 3;
        String dayType;
        
        switch (day) {
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
                dayType = "Working Day";
                break;
            case 6:
            case 7:
                dayType = "Weekend";
                break;
            default:
                dayType = "Invalid";
        }
        
        System.out.println("Day " + day + ": " + dayType);
    }
}
Output:
Day 3: Working Day

ရှင်းလင်းချက်:

  • case 1, 2, 3, 4, 5 အားလုံး "Working Day" output ပေးတယ်
  • case 1-4 မှာ break မပါဘူး → fall-through ဖြစ်တယ်
  • case 5 မှာမှ break ရှိလို့ ထွက်သွားတယ်
  • ဒီ pattern က multiple values အတွက် တူညီတဲ့ action လုပ်ဖို့ သုံးတယ်

🔹 String in Switch (Java 7+)

Java 7 ကနေစပြီး String ကိုလည်း switch မှာ သုံးလို့ရပါပြီ:

Java
public class BeverageMenu {
    public static void main(String[] args) {
        String drink = "Coffee";
        int price;
        
        switch (drink) {
            case "Coffee":
                price = 3000;
                System.out.println("Hot or Iced Coffee");
                break;
            
            case "Tea":
                price = 2000;
                System.out.println("Green or Black Tea");
                break;
            
            case "Juice":
                price = 3500;
                System.out.println("Fresh Fruit Juice");
                break;
            
            case "Soda":
                price = 2500;
                System.out.println("Coca Cola or Pepsi");
                break;
            
            default:
                price = 0;
                System.out.println("Not available");
        }
        
        System.out.println("Price: " + price + " Kyats");
    }
}
Output:
Hot or Iced Coffee
Price: 3000 Kyats

⚠️ String switch သတိပြုရန်:

  • Case-sensitive ဖြစ်တယ်: "coffee" နဲ့ "Coffee" မတူဘူး
  • null value ကို check လုပ်နိုင်မယ် (NullPointerException ရှောင်ရန်)
  • String comparison က equals() သုံးတယ် (== မဟုတ်ဘူး)

💻 Complete Example: Simple Calculator

Switch နဲ့ calculator လေး တည်ဆောက်ကြမယ်:

Java
public class SimpleCalculator {
    public static void main(String[] args) {
        double num1 = 10;
        double num2 = 5;
        char operator = '/';
        double result;
        
        System.out.println("=== Simple Calculator ===");
        System.out.println("Number 1: " + num1);
        System.out.println("Number 2: " + num2);
        System.out.println("Operator: " + operator);
        System.out.println();
        
        switch (operator) {
            case '+':
                result = num1 + num2;
                System.out.println("Addition: " + num1 + " + " + num2 + " = " + result);
                break;
            
            case '-':
                result = num1 - num2;
                System.out.println("Subtraction: " + num1 + " - " + num2 + " = " + result);
                break;
            
            case '*':
                result = num1 * num2;
                System.out.println("Multiplication: " + num1 + " × " + num2 + " = " + result);
                break;
            
            case '/':
                if (num2 != 0) {
                    result = num1 / num2;
                    System.out.println("Division: " + num1 + " á " + num2 + " = " + result);
                } else {
                    System.out.println("Error: Cannot divide by zero!");
                }
                break;
            
            case '%':
                if (num2 != 0) {
                    result = num1 % num2;
                    System.out.println("Modulus: " + num1 + " % " + num2 + " = " + result);
                } else {
                    System.out.println("Error: Cannot divide by zero!");
                }
                break;
            
            default:
                System.out.println("Error: Invalid operator!");
                System.out.println("Please use: +, -, *, /, %");
        }
    }
}
Output:
=== Simple Calculator ===
Number 1: 10.0
Number 2: 5.0
Operator: /

Division: 10.0 á 5.0 = 2.0

🔹 Practical Example: Days in Month

လ အမည်ကနေ ရက်ပေါင်း ထုတ်ပြခြင်း:

Java
public class DaysInMonth {
    public static void main(String[] args) {
        String month = "February";
        int year = 2024;
        int days;
        
        switch (month) {
            case "January":
            case "March":
            case "May":
            case "July":
            case "August":
            case "October":
            case "December":
                days = 31;
                break;
            
            case "April":
            case "June":
            case "September":
            case "November":
                days = 30;
                break;
            
            case "February":
                // Leap year check
                if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
                    days = 29;
                } else {
                    days = 28;
                }
                break;
            
            default:
                days = 0;
                System.out.println("Invalid month name!");
        }
        
        if (days > 0) {
            System.out.println(month + " " + year + " has " + days + " days.");
        }
    }
}
Output:
February 2024 has 29 days.

ဒီ example က ပြတာ:

  • Multiple cases အတွက် တူညီတဲ့ result (31 days, 30 days)
  • Switch case ထဲမှာ if statement သုံးခြင်း (February leap year)
  • Default case မှာ error handling
  • Real-world practical application

🔹 Switch vs If-Else-If: ဘယ်အချိန် ဘာသုံးရမလဲ?

Situation အကောင်းဆုံး Choice အကြောင်းပြချက်
တစ်ခု value ကို multiple values နဲ့ နှိုင်းယှဉ်ခြင်း Switch Clean, readable, faster
Range checking (x > 10 && x < 20) If-Else Switch က range မစစ်နိုင်ဘူး
Complex conditions (&&, ||) If-Else Switch က logical operators မသုံးနိုင်ဘူး
Equality checking (==) Switch More efficient
Boolean conditions If-Else Switch က boolean မသုံးနိုင်ဘူး
String/Char/Int equality Switch Cleaner code
Menu systems, day/month selection Switch Natural fit

General Rule:

Single variable ကို specific values တွေနဲ့ နှိုင်းယှဉ်ချင်ရင် → Switch

Complex conditions, ranges, multiple variables → If-Else

🔹 Modern Switch Expressions (Java 12+)

Java 12 ကနေ switch က expression အနေနဲ့ သုံးလို့ရပါပြီ - break မလိုတော့ဘူး!

Traditional Switch

Java (Old Style)
int day = 3;
String dayType;

switch (day) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        dayType = "Weekday";
        break;
    case 6:
    case 7:
        dayType = "Weekend";
        break;
    default:
        dayType = "Invalid";
}

Modern Switch Expression

Java 12+ (New Style)
int day = 3;

String dayType = switch (day) {
    case 1, 2, 3, 4, 5 -> "Weekday";
    case 6, 7 -> "Weekend";
    default -> "Invalid";
};

Modern switch ရဲ့ အားသာချက်များ:

  • break statement မလိုတော့ဘူး
  • Arrow syntax (->) သုံးတယ်
  • Multiple values ကို comma နဲ့ ခွဲလို့ရတယ်
  • Direct value assignment ရတယ်
  • Code က ပိုတိုပြီး ပို clean

Complex Logic with Yield

Java 12+ (Advanced)
int marks = 75;

String grade = switch (marks / 10) {
    case 10, 9 -> "A";
    case 8 -> "B";
    case 7 -> "C";
    case 6, 5 -> "D";
    default -> {
        if (marks < 0 || marks > 100) {
            yield "Invalid";
        } else {
            yield "F";
        }
    }
};

System.out.println("Grade: " + grade);

🎯 အဓိက မှတ်သားရမည့် အချက်များ

  • Switch statement: Variable တစ်ခုကို multiple values တွေနဲ့ တိုက်စစ်တယ်
  • Supported types: int, byte, short, char, String, enum (long, float, double မရဘူး)
  • break: Case တစ်ခု execute ပြီးရင် switch ကနေ ထွက်ဖို့ (အရေးကြီးဆုံး!)
  • Fall-through: break မပါရင် အောက်က cases တွေ ဆက် execute လုပ်တယ်
  • default: ဘယ် case နဲ့မှ မတူရင် execute လုပ်တယ် (optional ပေမယ့် သုံးသင့်တယ်)
  • Case values: Constant ဖြစ်ရမယ်၊ variables သုံးလို့ မရဘူး
  • Intentional fall-through: Multiple cases အတွက် တူညီတဲ့ code run ချင်ရင် သုံးတယ်
  • Switch vs If-Else: Equality checking အတွက် switch, complex conditions အတွက် if-else
  • Modern switch (Java 12+): Arrow syntax, break မလို, ပိုတိုပြီး clean

✍️ Practice Exercise

Exercise: Traffic Light System

Traffic light color အပေါ် မူတည်ပြီး action ပြသတဲ့ program ရေးပါ:

  • "Red" → "STOP! Wait for green light."
  • "Yellow" → "SLOW DOWN! Prepare to stop."
  • "Green" → "GO! Drive safely."
  • Any other → "ERROR! Invalid light color."

Bonus: "red", "RED", "Red" အားလုံး အလုပ်လုပ်အောင် ပြင်ပါ (case-insensitive)

💡 Solution ကြည့်ရန် (Try လုပ်ပြီးမှ ကြည့်ပါ)
Java
public class TrafficLight {
    public static void main(String[] args) {
        String light = "Yellow";
        
        // Convert to lowercase for case-insensitive matching
        String color = light.toLowerCase();
        
        System.out.println("Traffic Light: " + light);
        System.out.print("Action: ");
        
        switch (color) {
            case "red":
                System.out.println("STOP! Wait for green light.");
                System.out.println("⛔ Do not cross!");
                break;
            
            case "yellow":
                System.out.println("SLOW DOWN! Prepare to stop.");
                System.out.println("⚠️ Caution!");
                break;
            
            case "green":
                System.out.println("GO! Drive safely.");
                System.out.println("✅ Safe to proceed!");
                break;
            
            default:
                System.out.println("ERROR! Invalid light color.");
                System.out.println("Valid colors: Red, Yellow, Green");
        }
    }
}

📝 Quick Quiz

Question 1: Switch statement မှာ ဘယ် data type မသုံးနိုင်ဘူးလဲ?

Question 2: Break statement မပါရင် ဘာဖြစ်မလဲ?

Question 3: Default case က switch မှာ required လား?