When we want to execute different lines or blocks of code depending on the value of an individual variable, the switch statement is extremely effective. Now let's rewrite our series of if blocks using a switch statement instead. The syntax is explained in the following steps:
- We first declare that we're going to use a switch statement, switch being a reserved keyword in Java. Then, we provide the name of the variable that we'd like the switch statement to act on, in this case x because we're going to execute different blocks of code depending on the value of x:
package switcher; public class Switcher { public static void main(String[] args) { int x=1; switch(x) { } } }
Then, just like using an if