- Often while writing logic in the programming language, we come across situations when we need to execute particular logic based on user input.
For example, we need to read files based on user input and user input basically tells us what type of file needs to be read, for example, CSV, fixed length file format or parquet, Avro, etc.
- If you write the above logic without Switch, the only way is to use if else if which would make your code less readable, and on top of that each case would need to be checked.
- The switch has evolved over the years with new versions of Java switch expression has been introduced on java 12 and several changes have been made to it over time.
- Switch Expression allows us to write Switch block more efficiently improves the readability and is less error-prone.
- We use -> instead of a colon for cases.
- We don’t need a break statement so there are no fall-through cases. If we need to execute the same logic for several cases we can write so using -> operator.
- For example, in the below code, we can group all the weeks which require attendance, and another group that doesn’t require attendance.
- For multiline expression, we can use yield to return value.
we can use return instead of yield in order to avoid confusion whether the return is for multiline expression or switch statement. Hence yield is used to avoid confusion.
- Pattern matching was improved with enhancing feature in Java 14
- Traditionally, we would have to check for each data type with instanceof and then perform typecasting. This approach was too much verbose and the entire logic was dictated by type check and casting,
- With Java 14 we can improve code readability by checking the type and assigning to variable in a single line. Now we write less code to achieve the same amount of work which is also cleaner. think of the case when we have several type check, the traditional approach would be flooded with type check, cast, and assignment which will dictate the entire logic vs improved logic that basically reduce this verbosity
- With JEP 406, Pattern Matching with Switch Expression was added as a preview feature for Java 17