Heart containing Coding Chica Java 101

Switcharoo! The Java Switch Statement

TIP: References Quick List

In Java, another way that conditions can be checked is with a switch statement. This time, we want to check equality against one variable and the cases we want to test are possible values for that one variable. This works for primitive data types, wrapper classes for primitive data types, and Strings (Java 7+) and enumerated values (Enums – more on these later). The == test used in the switch comparisons don’t work well with other Objects, though.

The basic form of the switch statement requires an explicit break statement. Otherwise, the logic will continue to fall through to the next case and so on. Inside of the case, the logic will often do assignment, although it is not limited to just doing value assignments.

int dayOfWeekWithSundayFirst = 0;
boolean isWeekday = false;
switch (dayOfWeekWithSundayFirst) {
    case (1): 
        // Fallthrough - all weekdays
    case (2):
        // Fallthrough - all weekdays
    case (3): 
        // Fallthrough - all weekdays
    case (4): 
        // Fallthrough - all weekdays
    case (5):
        isWeekday = true;
        break;
    default:
       // This isn't strictly needed, as this is also the default value, but including it for completeness.
       isWeekday = false;
}

As a good practice, if you intentionally fall through a case to the next one, please include a comment indicating that it is intentional and possibly as to why. If you include the break statement within a case, then the switch’s logic will end when that break is reached.

A default section is optional. It is a catch-all if no other cases above were satisfied. This could provide a default value, throw an exception about the value received not being supported, or perform some default action.

The New Switch Statement

In newer versions of Java, an updated switch statement has emerged. In this example, we omit the break statement because the new syntax no longer requires it. Cases are grouped together explicitly with a single subsequent command:

int dayOfWeekWithSundayFirst = 0;
boolean isWeekday = switch (dayOfWeekWithSundayFirst) {
    case 1, 2, 3, 4, 5 -> true;
    default -> false;
}

Switcharoo! The Java Switch Statement

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.