Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

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 Go to all tips in Java Lessons by Jon Huhtala


Bookmark and Share
All Java Lessons contents page | Java Lesson 1 | Java Lesson 2 | Java Lesson 3 | Java Lesson 4 | Java Lesson 5 | Java Lesson 6 | Java Lesson 7 | Java Lesson 8 | Java Lesson 9 | Java Lesson 10 | Java Lesson 11 | Java Lesson 12 | Java Lesson 13 | Java Lesson 14 | Java Lesson 15 | Java Lesson 16 | Java Lesson 17 | Java Lesson 18 | Java Lesson 19 | Java Lesson 20 | Java Lesson 21 | Java Lesson 22 | Java Lesson 23 | Java Lesson 24 | Java Lesson 25 | Java Lesson 26 | Java Lesson 27 | Java Lesson 28 | Java Lesson 29 | Java Lesson 30 | Java Lesson 31 | Java Lesson 32 | Java Lesson 33 | Java Lesson 34 | Java Lesson 35 | Java Lesson 36 | Java Lesson 37 | Java Lesson 38 | Java Lesson 39 | Java Lesson 40 | Java Lesson 41 | Java Lesson 42 | Java Lesson 43 | Java Lesson 44 | Java Lesson 45 | Java Lesson 46

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;
}

  • Has a number subtleties and restrictions:

  1. 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.

  2. 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.

  1. 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).

  2. 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).

  • May be nested. A switch can be coded within another switch or in either leg of an if-else. It can also contain if-else code.

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:

  1. The balance, code, and amount variables hold data entered by the user.

  2. 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.

  3. 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.

  4. 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'.

  1. 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

  1. 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");
}

  1. a compile error will occur at line 2

  2. a compile error will occur at line 5

  3. Value is 5

  4. Value is 7

  5. Value is 7
    Some other value

  1. 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");
}

  1. a compile error will occur at line 1

  2. a compile error will occur at line 2

  3. the statements will compile successfully but a runtime error will occur at line 2

  4. Value is 5

  5. Some other value

  1. If the type of a switch expression is char, which of the following case statements are valid? (choose four)

  1. case 'x':

  2. case 'x' + 2:

  3. case 'x' - 3:

  4. case -3:

  5. case 128:

  1. Which of the following are invalid types for a switch expression? (choose four)

  1. boolean

  2. long

  3. short

  4. float

  5. double


 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy