Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are switch expressions and how are they different from switch statements?

As part of Java SE 12, switch expressions were introduced and since Java SE 14, they have been standardized. How are they different from switch statements?

like image 289
Arvind Kumar Avinash Avatar asked Jan 10 '21 18:01

Arvind Kumar Avinash


2 Answers

The switch statement:

Unlike the if/else if/else statement, a switch statement can have a number of possible execution paths. A switch works with the primitive types, byte, short, char, and int, their respective wrapper types (Byte, Short, Character, and Integer), enumerated types, and the String type1. While an if-else statement is used to test expressions based on ranges of values or conditions, a switch statement is used to test expressions based only on a single value.

Demo

enum PaymentStatus {
    UNPAID, PARTPAID, PAID, DISPUTED, UNKNOWN;
}

public class Main {
    public static void main(String[] args) {
        String message = "";
        PaymentStatus paymentStatus = PaymentStatus.PARTPAID;

        switch (paymentStatus) {
        case UNPAID:
            message = "The order has not been paid yet. Please make the minimum/full amount to procced.";
            break;
        case PARTPAID:
            message = "The order is partially paid. Some features will not be available. Please check the brochure for details.";
            break;
        case PAID:
            message = "The order is fully paid. Please choose the desired items from the menu.";
            break;
        default:
            throw new IllegalStateException("Invalid payment status: " + paymentStatus);
        }
        System.out.println(message);
    }
}

Output:

The order is partially paid. Some features will not be available. Please check the brochure for details.

The switch expression:

The switch expression was introduced with Java SE 12. However, it remained as a Preview feature in Java SE 12 and 13 and finally got standardized with Java SE 14. Like any expression, switch expressions evaluate to a single value, and can be used in statements. It also introduced "arrow case" labels eliminating the need for break statements to prevent fall through. As of Java SE 15, there is no change in the supported data types (mentioned in the switch statement section above).

Demo

enum PaymentStatus {
    UNPAID, PARTPAID, PAID, DISPUTED, UNKNOWN;
}

public class Main {
    public static void main(String[] args) {
        PaymentStatus paymentStatus = PaymentStatus.PARTPAID;

        String message = switch (paymentStatus) {
        case UNPAID -> "The order has not been paid yet. Please make the minimum/full amount to procced.";
        case PARTPAID -> "The order is partially paid. Some features will not be available. Please check the brochure for details.";
        case PAID -> "The order is fully paid. Please choose the desired items from the menu.";
        default -> throw new IllegalStateException("Invalid payment status: " + paymentStatus);
        };

        System.out.println(message);
    }
}

Output:

The order is partially paid. Some features will not be available. Please check the brochure for details.

The switch expression with yield:

Since Java SE 13, you can use yield statement, instead of the arrow operator (->), to return a value from a switch expression.

Demo

enum PaymentStatus {
    UNPAID, PARTPAID, PAID, DISPUTED, UNKNOWN;
}

public class Main {
    public static void main(String[] args) {
        PaymentStatus paymentStatus = PaymentStatus.PARTPAID;

        String message = switch (paymentStatus) {
        case UNPAID:
            yield "The order has not been paid yet. Please make the minimum/full amount to procced.";
        case PARTPAID:
            yield "The order is partially paid. Some features will not be available. Please check the brochure for details.";
        case PAID:
            yield "The order is fully paid. Please choose the desired items from the menu.";
        default:
            throw new IllegalStateException("Invalid payment status: " + paymentStatus);
        };

        System.out.println(message);
    }
}

Output:

The order is partially paid. Some features will not be available. Please check the brochure for details.

1 The support for String was added with JDK 7

like image 149
Arvind Kumar Avinash Avatar answered Sep 26 '22 00:09

Arvind Kumar Avinash


Nice writeup! But I might also add the ability to have multiple cases for a single case statement. The following example is very contrived (there are many better ways to achieve it). It does a simple frequency count of the vowels, digits, consonants, and other characters in a string.

int count[] = new int[4];

String s = "829s2bi9jskj*&@)(so2i2ksso";

for (char c : s.toCharArray()) {
      int i = switch (c) {
                case  'a', 'e', 'i', 'o', 'u' -> 0;
                case  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> 1;
                case  'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l',
                      'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w',
                      'x', 'y', 'z' -> 2;
                default -> 3;
      };
      count[i]++;
}
System.out.printf("vowels  - %d%n", count[0]);
System.out.printf("digits  - %d%n", count[1]);
System.out.printf("consonants - %d%n", count[2]);
System.out.printf("other   - %d%n", count[3]);

Prints

vowels  - 4
digits  - 7
consonants - 10
other   - 5
like image 23
WJS Avatar answered Sep 23 '22 00:09

WJS