DEV Community

Deepikandas
Deepikandas

Posted on

#19 Known is a Drop! Switch Statement in JAVA


The switch Statement :
Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths.
The body of a switch statement is known as a switch block.
A statement in the switch block can be labeled with one or more case or default labels.
The switch statement evaluates its expression, then executes all statements that follow the matching case label.

1. Classic Switch (Java 1.0 – 6)

  • Uses switch(expression) and case value: blocks.
  • Must use break to prevent fall-through.
  • Only supports int, byte, short, char (no String yet).
  • Fall-through occurs if break is omitted.
  • default can be anywhere inside Switch block -break statement in default is mandatory when default code is written in the middle of switch block.


2.Using Wrapper Classes in Switch:
Classic switch only allowed primitives (int, byte, char, short).
After Java 5, because of autoboxing, you can use wrapper classes like Integer, Byte, or Character in switch.
The compiler unboxes the object into the corresponding primitive internally.

3. Switch with Strings (Java 7+)

4.Enhanced Switch in Java 12 Preview → Java 14 Standard
Arrow syntax (->):
Like all expressions, switch expressions evaluate to a single value and can be used in statements. They may contain "case L ->" labels that eliminate the need for break statements to prevent fall through.

5. Switch Expression Returning Value (Java 14+)

  • Switch can return a value.
  • Use yield to return values from a block. yield can be used only in switch block.


6.Datatypes used in Switch expression and Case labels

  • boolean cannot be used, use if-else instead.
  • long, float, double cannot be used, even their wrappers.


**
Default statement must in switch block?**
1️⃣ In a traditional switch statement
default is optional.
If none of the case labels match and there is no default, the switch just does nothing and continues after the switch block.
2️⃣** In a switch expression (Java 14+)**
default is required only if the compiler can’t be sure all possible values are covered.
Why? Because a switch expression must return a value for every possible input. If the compiler sees that some inputs could be missing a value, it will throw an error.

Top comments (0)