Java Reference
In-Depth Information
the
main
method contains fewer lines of code than the
DrawBoxes2
program, consider
what would happen if you wanted to add a third box to the output. You would have to
add the five requisite
println
statements again, whereas in the programs that use the
drawBox
method you can simply add one more
println
and a third method call.
Java allows you to define methods in any order you like. It is a common conven-
tion to put the
main
method as either the first or last method in the class. In this text-
book we will generally put
main
first, but the programs would behave the same if we
switched the order. For example, the following modified program behaves identically
to the previous
DrawBoxes2
program:
1
public class
DrawBoxes3 {
2
public static void
drawBox() {
3 System.out.println("+------+");
4 System.out.println("| |");
5 System.out.println("| |");
6 System.out.println("+------+");
7 }
8
9
public static void
main(String[] args) {
10 drawBox();
11 System.out.println();
12 drawBox();
13 }
14 }
The
main
method is always the starting point for program execution, and from that
starting point you can determine the order in which other methods are called.
The
main
method is not the only place where you can call another method. In fact,
any method may call any other method. As a result, the flow of control can get quite
complicated. Consider, for example, the following rather strange program. We use
nonsense words (“foo,” “bar,” “baz,” and “mumble”) on purpose because the program
is not intended to make sense.
1
public class
FooBarBazMumble {
2
public static void
main(String[] args) {
3 foo();
4 bar();
5 System.out.println("mumble");
6 }
7
8
public static void
foo() {
9 System.out.println("foo");
10 }
Search WWH ::
Custom Search