Extremely Serious

Category: Java 14

Java Switch Expression

Syntax

switch(VARIABLE) {
	case MATCH_1 [, MATCH_2][, MATCH_N] -> EXPRESSION; | THROW-STATEMENT; | BLOCK
	default -> EXPRESSION; | THROW-STATEMENT; | BLOCK
}
Token Description
VARIABLE The variable to test.
MATCH_1, MATCH_2, MATCH_N The value or values that can match the VARIABLE.
EXPRESSION A expression to execute.
THROW-STATEMENT A expression that throws an exception.
BLOCK A block of statements to execute.

If a return value is required use the yield keyword instead of return.

Example

public enum Day { 
	SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; 
}

Day day = Day.WEDNESDAY;

int numLetters = switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> 6;
    case TUESDAY -> 7;
    case THURSDAY, SATURDAY -> {
        System.out.println(8);
        yield 8;
    }
    case WEDNESDAY -> {
        System.out.println(9);
        yield 9;
    }
    default -> {
        throw new IllegalStateException("Invalid day: " + day);
    }
};

System.out.println(numLetters);

ShowCodeDetailsInExceptionMessages Java Option

Use the following java option to have a more verbose exception message especially for NullPointerException:

-XX:+ShowCodeDetailsInExceptionMessages

For example, if we have the following snippet:

var a = null;
a.b = 1;

Running the above snippet will have the following exception:

Exception in thread "main" java.lang.NullPointerException: Cannot assign field "b" because "a" is null

Note: This is more useful if the classes were compiled with debugging info (i.e. javac -g )