break is used to terminate the case, if it is not used then it goes to the next case and executes
break in last case is optional, but recommended for consistency
Arguments
null is not allowed, it throws NullPointerException if it is null
The following are allowed
byte and Byte
short and Short
int and Integer
char and Character
enum
String
case
constants are generally used
variables if used should be final
comparison
For String, it uses equals() method
String result;switch (animal) { case "DOG": case "CAT": result = "domestic animal"; break; case "TIGER": result = "wild animal"; break; default: result = "unknown animal"; break;}
Switch Expression
Introduced in Java 14+
There is no break statement and hence it does not fall through cases
var result = switch(month) { case JANUARY, JUNE, JULY -> 3; case FEBRUARY, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER -> 1; case MARCH, MAY, APRIL, AUGUST -> 2; default -> 0; };
Use yield to return the data
var result = switch (month) { case JANUARY, JUNE, JULY -> 3; case FEBRUARY, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER -> 1; case MARCH, MAY, APRIL, AUGUST -> { int monthLength = month.toString().length(); yield monthLength * 4; } default -> 0;};
return can be used but then you should not store the data in result
private static int test(Month month) { switch (month) { case JANUARY, JUNE, JULY -> { return 3; } // returns from the test() default -> { return 0; } }}// This is wrong!!!private static int test(Month month) { var result = switch (month) { // compilation error cannot store or return case JANUARY, JUNE, JULY -> { return 3; } default -> { return 0; } } return result;}
Switch statements are not exhaustive, but switch expressions must be exhaustive as per compiler
Pattern matching
Introduced in Java 21+
Available for switch statements and expressions
Type checks can be added which internally uses instanceof
Guarded Patterns can be used using when keyword
null case can be added to avoid NullPointerException
static double getDoubleUsingSwitch(Object o) { return switch (o) { // Type matching case Integer i -> i.doubleValue(); case Float f -> f.doubleValue(); // Type matching with Guarded case case String s when s.length() > 0 -> Double.parseDouble(s); // null case case null -> 0d; // default case default -> 0d; };}