|
|
So far, within each method we've used sequential execution only, executing one statement after another. Like other languages, Java(TM) provides language constructs for conditional execution, specifically, if, switch, and the conditional operator ?.
The more general construct, if has the syntax:
if (<boolean-expression>)
<statement>...
where <statement>... can be one statement, for example,
x = 4;
or multiple statements grouped within curly brackets (a statement group), for example,
{
x = 4;
y = 6;
}
and <boolean-expression> is any expression that evaluates to a boolean value, for example,
If the Boolean expression evaluates to true, the statement (or statement group) following the if clause is executed. Java also supports an optional else clause; the syntax is:
if (<boolean-expression>)
<statements>...
else
<statements>...
If the Boolean expression evaluates to true, the statement (or statement group) following the if clause is executed; otherwise, the statement (or statement group) following the else clause is executed. Boolean expressions often include one or more Java comparison operators, which are listed in the following table:
Returning to our user-defined type Dog, we can add additional state variables for more flexible representation of real-world objects. Suppose we add instance variables gentle and obedienceTrained, which can be true or false:
class Dog {
String barkSound = new String("Woof.");
boolean gentle = true;
boolean obedienceTrained = false;
...
In Java, Boolean values are literals (case is significant), and boolean variables accept either value. For gentle and obedienceTrained there are no new operators because we're not creating objects--we're creating primitive variables and assigning them the default values true and false. Access methods provide the flexibility for modifying these instance variables on a dog-by-dog basis:
void setGentle(boolean gentle) {
this.gentle = gentle;
}
void setObedienceTrained(boolean trained) {
obedienceTrained = trained;
}
Note that the reference to obedienceTrained in setObedienceTrained() does not require qualification with this because there is no local variable by the same name. copyright 1996-2000 Magelang Institute dba jGuru |
|