O'Reilly logo

Java Programming for Beginners by Mark Lassoff

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required