|
|
|
1000 Java Tips ebook
|
|
 

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java
programming articles and tips. Please take your copy here.
Take your copy of free "Java Technology Screensaver"!. |
|
The Java Lesson 9: switch statements
|
JavaFAQ Home » Java Lessons by Jon Huhtala

The Java Lesson 9
switch
statements
Overview
Flow control with if and else
statements gets cumbersome when a variable must be tested for a large number of
possible values, such as a menu selection that permits the user to enter an
integer from 1 to 20. The solution to this problem is the switch statement.
The switch statement
-
Specifies an expression whose value is be
tested. This is known as the "switch expression" and is typically the name of
a single variable.
-
Defines a number of "cases", each associated
with a different value. There may also be a "default" case that is not
associated with a value. If the value of the switch expression is equal to the
value of a case, the statements for that case will be executed. Otherwise, the
statements of the default case will be executed.
- General syntax:
switch
(expression) {
case value1:
statements;
break; case value2:
statements;
break; default:
statements;
break; }
-
The switch expression must be a primitive of type int or able to be promoted to
int. Specifically, it
must be either byte,
short, int, or char. Expressions of type
boolean, long, float, and double will not compile.
-
The value specified on a case must be a constant of type int or must be able to be
promoted to int (in
other words a byte,
short, int, or char). It must also be within
the possible range of values of the switch expression. For example, if the switch variable is a byte, a case with a value of 200 would not compile because a byte may only have a value
from -128 to 127.
The value of a case may be an expression as long as the result
is a constant. For example,
case 5 +
1:
would compile successfully.
-
The break
statement is optional and will be covered in more detail in a later lesson.
When encountered, it ends the execution of the switch statement. If omitted from a case, processing falls
through to the next case (a sometimes undesirable result).
-
Although the compiler doesn't care, cases should be arranged
in a high probability to low probability order to enhance processing
efficiency. The default
can be placed anywhere (even first).
Example
The following program is a revised version of the nested if-else sample from the previous lesson:
public class App
{ public static void main(String[] args) {
// Variables
double balance;
char code; double amount;
//
Prompt for and read data
System.out.print("Enter
customer's starting balance: "); balance =
Keyboard.readDouble(); System.out.print("Enter
transaction amount: "); amount =
Keyboard.readDouble(); System.out.println("Transaction
codes are"); System.out.println(" " + "C -
charge"); System.out.println(" " + "P -
payment"); System.out.println(" " + "R - refund or
return"); System.out.print("Enter transaction code:
"); code =
Keyboard.readChar();
// Process based upon
transaction code
switch (code)
{ case
'C': case
'c': balance +=
amount; System.out.println("New
balance is " +
Utility.moneyFormat(balance));
break; case
'P': case
'p': balance -=
amount; System.out.println("New
balance is " +
Utility.moneyFormat(balance));
break; case
'R': case
'r': balance -=
amount; System.out.println("New
balance is " +
Utility.moneyFormat(balance));
break;
default:
System.out.println("Invalid transaction
code");
break; } } }
Notes:
-
The balance, code, and amount variables hold data entered by the user.
-
After all data has been read from
the user, the transaction is processed by the switch statement with the transaction code
(code) used as the
switch expression.
-
Within the switch, if the value of code matches the value of a
particular case,
processing jumps to the statement block for that case, otherwise processing jumps to the
statement block for the default. Processing will then continue until either a break statement is
encountered or the end of the switch is reached.
-
Stacking two or more cases without
at break statement
constitutes an OR. For example,
case 'R': case 'r':
will result in the same processing
being performed if the value of code is either an uppercase or lowercase 'R'.
-
For transactions with a valid
transaction code, the customer's new balance is displayed using the moneyFormat() method of my
Utility class. If the
transaction code is bad, an error message is displayed.
Review questions
-
Assuming that all unseen
code is correct and that line numbers are for reference purposes only, what
will result from an attempt to compile and execute the following statements?
1 2 3 4 5 6 7 8 9 |
int j = 5; switch (j + 2) { case
5: System.out.println("Value is 5");
case 6 + 1: System.out.println("Value is
7"); default: System.out.println("Some
other value"); } |
-
a compile error will occur
at line 2
-
a compile error will occur
at line 5
-
Value is 5
-
Value is 7
-
Value is 7 Some other value
-
Assuming that all unseen
code is correct and that line numbers are for reference purposes only, what
will result from an attempt to compile and execute the following statements?
1 2 3 4 5 6 7 8 9 10 11 |
double x = 5.0; switch (x) { case
5: System.out.println("Value is
5"); break; case
7: System.out.println("Value is
7"); break;
default: System.out.println("Some other
value"); } |
-
a compile error will occur
at line 1
-
a compile error will occur
at line 2
-
the statements will
compile successfully but a runtime error will occur at line 2
-
Value is 5
-
Some other value
-
If the type of a switch expression is char, which of the following case statements are valid? (choose
four)
-
case 'x':
-
case 'x' + 2:
-
case 'x' - 3:
-
case -3:
-
case 128:
-
Which of the following are
invalid types for a switch
expression? (choose four)
-
boolean
-
long
-
short
-
float
-
double Printer Friendly Page
Send to a Friend
..
Search here again if you need more info!
|
|
|