Java Reference
In-Depth Information
The initial value for clothes corresponds to socks and in a more practical example would be arrived at
by means other than just assigning the value. You use the clothes variable to control the next switch
statement. For each case in the switch , you output what is to be washed and set the value for the wash
variable to the appropriate enumeration constant. You would usually put a default case in this sort of
switch statement because its control expression is numeric, and if the value was derived by some com-
putation or other, there is always the possibility of an invalid value being produced. If there is no default
case and the switch expression results in a value that does not correspond to any of the cases, execution
just continues with the statement following the switch block.
After the first switch , you output the wash type:
System.out.println("Wash is "+ wash);
You saw in the previous chapter that the string representation of a value that is an enumeration constant
is the name of the value as it appears in the type definition.
Lastly, you use the wash variable as the expression selecting a case in the next switch . Because a variable
of an enumeration type must have an enumeration constant as a value, and all possible values are repres-
ented by cases in the switch , you don't need a default case here.
Note that you could have defined the values for the various types of clothes as constant values:
final int SHIRTS = 1;
final int SWEATERS = 2;
final int SOCKS = 3;
final int SHEETS = 4;
final int PANTS = 5;
The value set for the clothes variable would then have been much more obvious:
int clothes = SOCKS;
Of course, you could also have used an enumeration for the clothes type, too, but I'll leave you to work
out what that would look like.
VARIABLE SCOPE
The scope of a variable is the part of the program over which the variable name can be referenced — in other
words, where you can use the variable in the program. Every variable that I have declared so far in program
examples has been defined within the context of a method, the method main() . Variables that are declared
within a method are called local variables , as they are only accessible within the confines of the method in
which they are declared. However, they are not necessarily accessible everywhere in the code for the meth-
od in which they are declared. Look at the next code fragment, which shows variables defined within nested
blocks:
{
int n = 1; // Declare and define n
// Reference to n is OK here
// Reference to m here is an error because m does not exist yet
Search WWH ::




Custom Search