Java(TM) provides the while, do-while, and for language constructs for iterating over a statement (or statement group) multiple times. while is the more general iterative construct; for is the more syntactically powerful.
Iterative Constructs |
while (<boolean-expression>) <statements>...
|
do <statements>... while (<boolean-expression>)
|
for (<init-stmts>...; <boolean-expression>; <exprs>...) <statements>... |
With iteration, we can (to the dismay of our neighbors) make barking behavior repetitive:
void bark(int times) {
while (times > 0) {
System.out.println(barkSound);
times = times - 1;
}
}
Thus, with yet another bark() method, we support the object-oriented task of sending a Dog instance the bark message, accompanied with a message request (method argument) for n barks, represented in the method definition by the parameter times.
DogChorus now begins to reflect its name:
public class DogChorus {
public static void main(String[] args) {
Dog fido = new Dog();
Dog spot = new Dog();
spot.setBark("Arf. Arf.");
fido.bark();
spot.bark();
fido.bark(4);
spot.bark(3);
new Dog().bark(4); // unknown dog
System.exit(0);
}
}
DogChorus now displays the following:
Woof.
Arf. Arf.
Woof.
Woof.
Woof.
Woof.
Arf. Arf.
Arf. Arf.
Arf. Arf.
Woof.
Woof.
Woof.
Woof.
Note the line in the source code with the comment "// unknown dog". As we mentioned, Java is a dynamic language, another example of which we illustrate here. An "unnamed" Dog is instantiated on the fly (appears suddenly from down the street), joins in the chorus, and then disappears.
That is, with Java we can create an instance of any class on the fly, without assigning it to a reference variable for future use (assuming we need it only once), and use it directly. Furthermore, the Java syntax and order of evaluation for "new <data-type>()" is designed so that we can do this without having to group the new operation in parentheses.
copyright 1996-2000 Magelang Institute dba jGuru