Java Reference
In-Depth Information
program uses the
drawBox
method to produce the same output as the original
DrawBoxes
program:
1
public class
DrawBoxes2 {
2
public static void
main(String[] args) {
3 drawBox();
4 System.out.println();
5 drawBox();
6 }
7
8
public static void
drawBox() {
9 System.out.println("+------+");
10 System.out.println("| |");
11 System.out.println("| |");
12 System.out.println("+------+");
13 }
14 }
The most confusing thing about static methods is that programs with static methods
do not execute sequentially from top to bottom. Rather, each time the program
encounters a static method call, the execution of the program “jumps” to that static
method, executes each statement in that method in order, and then “jumps” back to
the point where the call began and resumes executing. The order in which the state-
ments of a program are executed is called the program's
flow of control.
Flow of Control
The order in which the statements of a Java program are executed.
Let's look at the control flow of the
DrawBoxes2
program shown previously. It has
two methods. The first method is the familiar
main
method, and the second is
drawBox
. As in any Java program, execution starts with the
main
method:
public static void main(String[] args) {
drawBox();
System.out.println();
drawBox();
}
In a sense, the execution of this program is sequential: Each statement listed in the
main
method is executed in turn, from first to last.
But this
main
method includes two different calls on the
drawBox
method. This
program will do three different things: execute
drawBox
, execute a
println
, then
execute
drawBox
again.
Search WWH ::
Custom Search