How to Use a Switch Statement
The switch statement is used in programming languages such as C, C++, Javascript and Java. When you desire to code a logical string of checking variable conditions and performing different actions depending on the value of the variable, you have two choices: 1) Using a string of if-then-else statements; or 2) Using a switch statement to execute a "case" value that matches the variable's value. The type of variable that a switch statement can check depends on the programming language. All languages are able to use the integer primitive data types. Java, which is used in this example, is able to use a switch statement for data types that include byte, short, char and int, as well as the object types character, byte, short and integer.
Instructions
-
-
1
Download and install the latest Java Standard Developer's Kit if not already installed.
-
2
Open a text editor and enter the following text to instantiate the demo code:
Public class mySwitchDemo
{
Public static void -
-
3
This example has nine integer values possible to switch on the assigned variable. Assign a value to the integer variable inning of four, followed by starting the switch statement to use that variable for the condition check.
Int inning = 4;
Switch (inning)
{ -
4
The case statements compose the "switch" block of the switch statement. Each case must finish with the "break" statement, or the programming flow will automatically execute each successive case until it encounters a break or the final case is executed. In this example, the word "Fourth" will print to the command console when executed. The default case is executed if none of the previous case statements are used.
Case 1: System.out.println("First"); break;
Case 2: System.out.println("Second"); break;
Case 3: System.out.println("Third"); break;
Case 4: System.out.println("Fourth"); break;
Case 5: System.out.println("Fifth"); break;
Default: System.out.println("Extra Innings"); break;
}// end Switch
}//end Main
}//end Class
-
1