Let’s say that you want to set variable y to different values based on the value of variable x. You could write an if statement with several else-if  clauses.

int x = 9, y = 7;

if (x == 2)
    y = 4;
else if (x == 9)
    y = 5;
else if (x == 5)
   y = 6;

System.out.println(y);                // Prints 5


You could also implement a switch statement.


Section 1 - switch Statements


switch statement is a construct that executes different statement blocks based on discrete values of a variable. It is said to “switch” on a variable. The format of a switch statement is as follows:


        switch (variable_name)


                case value1:

                        statement block 1

                case value2:

                        statement block 2




The keyword switch is followed by a variable enclosed in parentheses. This is followed by the body of the switch statement enclosed in curly braces. Inside the switch body, discrete variable values are listed as cases (the keyword case followed by a value followed by a colon). Statement blocks may follow each case.




Copyright ©2017 by Ralph Lecessi Incorporated. All rights reserved.