This article helps you understand and use the switch case construct in Java with code examples.

The switch-case construct is a flow control structure that tests value of a variable against a list of values. Syntax of this structure is as follows:

switch (expression) {
    case constant_1:
        // statement 1
        break;
    case constant_2:
        // statement 2
        break;
    case constant_3:
        // statement 3
        break;
    //...
    case constant_n:
        // statement n
        break;
    default:
        // if all the cases do not match
}
 

Some Rules about switch-case construct:

Some Java switch-case examples:

          The following example shows a switch statement that tests for an integer variable. It products the output: The number is Three

int number = 3;

String text = "";

switch (number) {
    case 1:
        text = "One";
        break;
    case 2:
        text = "Two";
        break;
    case 3:
        text = "Three";
        break;
    default:
        text = "Other number";
}

System.out.println("The number is: " + text);
 

 The following example shows a switch statement that tests for a String variable, without a default block. It will output: The distance from earth to Jupiter is: 4

String planet = "Jupiter";

long distanceFromEarth = 0;

switch (planet) {
    case "Mars":
        distanceFromEarth = 3;
        break;
    case "Saturn":
        distanceFromEarth = 5;
        break;
    case "Jupiter":
        distanceFromEarth = 4;
        break;
    case "Venus":
        distanceFromEarth = 1;
        break;
}

System.out.println("The distance from earth to " + planet + " is: " + distanceFromEarth);
 

          The following example shows a switch statement that tests for an enum type, Priority. It will output the result: Task priority: 3

Priority priority = Priority.HIGH;

int taskPriority = 0;

switch (priority) {
    case LOW:
        taskPriority = 1;
        break;
    case NORMAL:
        taskPriority = 2;
        break;
    case HIGH:
        taskPriority = 3;
        break;
    case SEVERE:
        taskPriority = 4;
        break;
}

System.out.println("Task priority: " + taskPriority);
The enum Priority is declared as follows:

public enum Priority { LOW, NORMAL, HIGH, SEVERE }
 

From Java 14, you can use switch block as an expression. For example:

int taskPriority = switch (priority) {
    case LOW -> 1;
    case NORMAL -> 2;
    case HIGH -> 3;
    case SEVERE -> 4;
};

System.out.println("Task priority: " + taskPriority);
Learn more: Java 14: Switch Expressions Enhancements Examples

 

Related Topics:



 

Other Recommended Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.