In Java switch statements are used instead of multiple if-else statements. Something like below
case "Monday" -> System.out.println("Today is an monday");
case "Tuesday" -> System.out.println("Today is an tuesday");
case "Wednesday" -> System.out.println("Today is an wednesday");
case "Thursday" -> System.out.println("Today is an thursday");
case "Friday" -> System.out.println("Today is an friday");
case "Saturday" -> System.out.println("Today is an saturday");
case "Sunday" -> System.out.println("Today is an sunday");
default -> System.out.println("Invalid date");
}
There are multiple advantages of this we dont' need to write multiple nested if-else block
System.out.println("Today is an monday");
}
else if ("Tuesday".equals(day)) {
System.out.println("Today is an tuesday");
}
......
else {
System.out.println("Invalid date");
}
Switch statements are there in java for a long back. over time it has evolved. Earlier Switch expressions are supposed to be numbers or enums. Case statements used to start with : and break need to be added to stop the overflow
case "Monday": System.out.println("Today is an monday"); break;
case "Tuesday": System.out.println("Today is an Tuesday"); break;
.....
}
In Java 17 switch is enhanced. Before Java 17 switch started supporting string as expression type. In 17 the case key word can be followed with -> so that we dont need break any more.
we can have multiple levels in case.
We can return value from the case using yield
case "Monday" -> {
yield 1;
}
case "Tuesday" -> {
yield 2;
}
default -> {
yield -1;
}
};
In case expression we can try an instance of the operator or null check also
switch (x) {
case null -> System.out.println("x is null");
case Integer i -> System.out.println("x is an integer");
default -> System.out.println("x is of type "+x.getClass().getName());
}
These are still preview features to try this we need to enable it in our java env
java --enable-preview --source 17 <filename.java>
Please let me know your thoughts about this topic.
Reference
https://docs.oracle.com/en/java/javase/17/language/pattern-matching-switch-expressions-and-statements.html#GUID-E69EEA63-E204-41B4-AA7F-D58B26A3B232
No comments:
Post a Comment
Thanks.