Program using switch, case, and break

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:

  1. 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

Get Java Programming for Beginners now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.