Java Reference
In-Depth Information
The first method that is invoked in your Java program is main(), which is
invoked by the JVM. Therefore, main() is at the bottom of your method call
stack.
Suppose that main() invokes a method called turnOn(), and the turnOn()
method invokes a setVolume() method, which in turn invokes the println()
method. Because println() is at the top of the call stack, the flow of control is
currently within println(). The setVolume() method is waiting for println() to
finish, the turnOn() method is waiting for setVolume() to finish, and so on
down the call stack.
A Java program can have more than one call stack if it is a multithreaded
application, but all the programs so far in this topic have a single call
stack. We will discuss multithreaded applications in Chapter 15, “Threads.”
Invoking Methods
A method is invoked, causing it to be placed at the top of the call stack until it
is finished executing. When a method is done executing, three things can occur:
The method returns a value, in which case a primitive data type or
reference is passed back to the caller of the method.
■■
The method does not return a value, in which case the return value is
declared as void.
■■
The method throws an exception, which is thrown back to the caller
of the method. Exceptions are discussed in Chapter 11, “Exception
Handling.”
■■
In all three of these cases, the flow of control jumps back to the caller of the
method. To demonstrate the flow of control of methods, let's look at an example.
The following Date class is a simple class that could be used to represent a cal-
endar date. How many fields does the Date class have? How many methods?
public class Date
{
public int day, month, year;
public int getDay()
{
System.out.println(“Inside getDay method”);
return day;
}
public void printDate()
{
System.out.println(“Inside printDate method”);
Search WWH ::




Custom Search