diff --git a/04_Control_structures/control_structures.md b/04_Control_structures/control_structures.md index afc0c63..4e344dd 100644 --- a/04_Control_structures/control_structures.md +++ b/04_Control_structures/control_structures.md @@ -262,6 +262,64 @@ Output It is 20 ``` +The new **switch expression** syntax in Java, introduced in Java 14 as a standard feature, simplifies `switch` blocks by allowing them to return a value and uses the `->` operator for cases, eliminating the need for explicit `break` statements. + +Example of New Switch Syntax: + +Here's a short example comparing the traditional and new syntax for calculating the number of days in a given month (ignoring leap years for simplicity): + +Traditional Syntax (Statement): + +```java +int month = 2; // February +int days; + +switch (month) { + case 1: + case 3: + case 5: + case 7: + case 8: + case 10: + case 12: + days = 31; + break; + case 4: + case 6: + case 9: + case 11: + days = 30; + break; + case 2: + days = 28; + break; + default: + days = 0; // Invalid month +} +// days is 28 +``` + +New Syntax (Expression): + +```java +int month = 2; // February + +int days = switch (month) { + case 1, 3, 5, 7, 8, 10, 12 -> 31; + case 4, 6, 9, 11 -> 30; + case 2 -> 28; + default -> 0; // Invalid month +}; +// days is 28 +``` + +The new syntax, often called a **switch expression**, provides several key benefits: + +1. **Value Production:** It can be used as an expression, meaning the entire `switch` block returns a value, which is immediately assigned to the `days` variable. +2. **Arrow Label (`->`):** The `case` labels now use the **arrow** (`->`) instead of a colon (`:`). This arrow signifies that only the expression or block of code to its right will be executed for that case. +3. **No Fall-Through/Break:** Because the arrow only executes the code to its right, there is **no automatic fall-through** to the next case. This eliminates the common source of bugs caused by forgetting a `break` statement. +4. **Multiple Labels:** Multiple case constants can be listed, separated by commas (e.g., `case 1, 3, 5, ...`), making case grouping more concise. + # Jump Java supports three jump statements: ```break```, ```continue``` and ```return```.