Completion requirements
Read this chapter, which discusses the switch and '?' operators to write conditional statements. As you read this tutorial, you will learn that sometimes it is better to use a 'switch' statement when there are multiple choices to choose from. Under such conditions, an if/else structure can become very long, obscure, and difficult to comprehend. Once you have read the tutorial, you will understand the similarity of the logic used for the 'if/else' statement, '?', and 'switch' statements and how they can be used alternately.
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
?