Java Reference
In-Depth Information
The diagram below indicates the flow of control produced by this program.
public static void main(String[] args) {
drawBox();
public static void drawBox() {
System.out.println("+------+");
System.out.println(" ");
System.out.println(" ");
System.out.println("+------+");
}
System.out.println();
drawBox();
public static void drawBox() {
System.out.println("+------+");
System.out.println(" ");
System.out.println(" ");
System.out.println("+------+");
}
}
Following the diagram, you can see that nine println statements are executed.
First you transfer control to the drawBox method and execute its four statements.
Then you return to main and execute its println statement. Then you transfer con-
trol a second time to drawBox and once again execute its four statements. Making
these method calls is almost like copying and pasting the code of the method into the
main method. As a result, this program has the exact same behavior as the nine-line
main method of the DrawBoxes program:
public static void main(String[] args) {
System.out.println("+------+");
System.out.println("| |");
System.out.println("| |");
System.out.println("+------+");
System.out.println();
System.out.println("+------+");
System.out.println("| |");
System.out.println("| |");
System.out.println("+------+");
}
This version is simpler in terms of its flow of control, but the first version avoids the
redundancy of having the same println statements appear multiple times. It also gives
a better sense of the structure of the solution. In the original version it is clear that there
is a subtask called drawBox that is being performed twice. Also, while the last version of
 
Search WWH ::




Custom Search