vasanth0989 / prep-myself

0 stars 0 forks source link

Switch case - Conditional Statement #7

Open vasanth0989 opened 10 months ago

vasanth0989 commented 10 months ago
public class TestMain {

    public static void main(String[] args) {
        System.out.println(getMonthByNameWithElseIf("JAN"));
        // what's the problem with else-if??
        // when to use switch-case
        // The logic is simple, in your else-if statement if you are switching with a single value
        // then YES you have to use switch/case
        System.out.println(getMonthNameUsingSwitchCase("feb"));
    }

    static int getMonthByNameWithElseIf(String monthName) {
        int num = 0;
        if ("jan".equalsIgnoreCase(monthName)) {
            num = 1;
        } else if ("feb".equalsIgnoreCase(monthName)) {
            num = 2;
        } else if ("mar".equalsIgnoreCase(monthName)) {
            num = 3;
        } else {
            throw new RuntimeException("Provided month does not exist");
        }
        return num;
    }

    static int getMonthNameUsingSwitchCase(String monthName) {
        int num = 0;
        switch (monthName.toLowerCase()) {
            case "jan":
                num = 1;
                // In a switch case statement break is mandatory!!
                break;
            case "feb":
                num = 2;
                break;
            case "mar":
                num = 3;
                break;
            default:
                throw new RuntimeException("Provided month does not exist");
        }
        return num;
    }

}