Show example of switch expressions and multi-label case statements

The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. The switch statement works with byte, short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long.


Approach: Integer switch

Java


public class SwitchCaseTest {
    public static void main(String[] args) {
        int num = 1;
        switch (num) {
        case 1:
            System.out.println("One");
            break;
        case 2:
            System.out.println("Two");
            break;
        case 3:
            System.out.println("Three");
            break;
        default:
            System.out.println("Default");
        }
    }
}

Approach: String Switch

Java


public class SwitchCaseTest {
    public static void main(String[] args) {
        String month = "Mar";
        switch (month) {
        case "Jan":
            System.out.println("January");
            break;
        case "Feb":
            System.out.println("Feb");
            break;
        case "Mar":
            System.out.println("March");
            break;
        default:
            System.out.println("Default");
        }
    }
}

Approach: Nested Switch

Java


public class SwitchCaseTest {
    public static void main(String[] args) {
        int num = 1;
        int n = 2;
        switch (num) {
        case 1:
            System.out.println("One");
            switch (n) {
            case 1:
                System.out.println("One One");
            case 2:
                System.out.println("One Two");
            }
            break;
        case 2:
            System.out.println("Two");
            break;
        case 3:
            System.out.println("Three");
            break;
        default:
            System.out.println("Default");
        }
    }
}



No comments:

Post a Comment