Lesson+10


 * Lesson #10: "switch" Statements and char - Chris**

Instead of using if statements, a programmer may choose to use the "switch" statement. One useful application for the "switch" statement is as code for a software menu with multiple choices, though other uses are possible. Though similar to the "if" statement, the "switch" statement only allows for two data input types, "int" and "char". Typical format is as follows: code switch(var) //var is the (arbitrary) variable used in the statement {     choice 1: System.out.println("Nice choice!!"); break; choice 2: System.out.println("Not so good..."); break; default: System.out.println("Choose 1 or 2!!!"); } code As in an "if" statement, "var" (or whatever you choose) is the argument. Its value when the "switch" statement is carried out determines what will be executed. **This variable may only be an "int" or a "char"** (or "short" or "byte", but these are uncommon). The programmer chooses the desired values of the variable so that certain commands will be executed, as in this piece of code: code choice 1: System.out.println("Nice choice!!"); break; code The "1" after "choice" means that if the value of the argument is 1, the code following the initial line will be executed. In this case, words are printed, though all other potential operations can be carried out so long as the associated variable types are compatible. The "break" tells the program to stop execution of the "switch" statement after the "println" command. If it is left out, further choices will also be executed, until a "break" command appears, or the "switch" statement ends. The "default" command (as seen in the first set of code on this page) acts as a "choice", but for all possible values of the argument not listed by the programmer.

"char" variables can be anything, including numbers and symbols, and are declared with single quotes, as in the following examples: code char a = '#'; char kk = 's'; char omNom = '8'; code
 * The "char " data type**