The Conditional Operator and the 'switch' Statement
6. Rules for switch Statements
Answer:
0.2
Rules for switch
Statements
switch
StatementsHere is what a switch statement looks like:
|
Here is how it works:
- Only one case is selected per execution of the
switch
statement. - The value of
expression
determines which case is selected. expression
must evaluate to byte, short, char, or int primitive data, aString
, or a few other types not discussed further here.- The type of
expression
and the type of thelabel
s must agree. - Each
label
must be an integer literal (like 0, 23, or 'A'), aString
literal (like "green"), but not an expression or variable. - There can be any number of statements in a
statementList
. - The
statementList
is usually followed withbreak;
- Each time the
switch
statement is executed, the following happens:- The
expression
is evaluated. - The
label
s after eachcase
are inspected one by one, starting with the first. - The first label that matches has its
statementList
execute. - The statements execute until a
break
statement is encountered. - Now the entire
switch
statement is complete (no further statements are executed.)
- The
- If no case label matches the value of
expression
, then thedefault
case is picked, and its statements execute. - If no case label matches the value of
expression
, and there is nodefault
case, no statements execute.
Question 6:
Could the type of the expression
be a float
or a double
?