Java Reference
In-Depth Information
The case constant does not require tic marks when the control state-
ment evaluates to an int type. The following code fragment shows a case
construct in which the switch variable is of type int.
int intVar;
...
switch (intVar)
{
case 1:
System.out.println("Input was 1");
break;
case 2:
System.out.println("Input was 2");
break;9
...
}
The break keyword is optional, but if it is not present at the end of a
case block, then the following case or default blocks execute. In other
words, execution in a switch construct continues until a break keyword
or the end of the construct is encountered. When a break keyword is en-
countered, execution is immediately directed to the end of the switch
construct. A break statement is not required on the last block (case or de-
fault statement), although the break is usually included to make the code
easier to read.
The blocks of execution within a switch construct are enclosed in ros-
ters; however, the case and the default keywords automatically block the
statements that follow. Rosters are not necessary to indicate the
first-level execution block within a case or default statement.
The following program shows the processing necessary for implement-
ing menu selection using a Java switch construct.
On the Web
The MenuDemo.java program is found in the Chapter 9 folder at
www.crcpress.com .
//
File name: MenuDemo.java
//
Reference: Chapter 9
//
//
Java program to demonstrate menu selection
//
Topics:
//
1. Using the switch construct
//
//
Requires:
//
1. Keyin class in the current directory
Search WWH ::




Custom Search