Java Reference
In-Depth Information
To execute this method, we take out the sheet of paper with drawTriangle on it
and place it on top of the drawTwoTriangles sheet:
public static void main(String[] args) {
drawTriangle();
public static void drawTwoTriangles() {
drawTwoTriangles();
drawTriangle();
public static void drawTriangle() {
System.out.println(" *");
System.out.println(" ***");
System.out.println("*****");
System.out.println();
}
}
drawTwoTriangles();
}
This diagram makes it clear that we started with the method main , which called
the method drawTwoTriangles , which called the method drawTriangle . So, at this
moment in time, three different methods are active. The one on top is the one that we
are actively executing. Once we complete it, we'll go back to the one underneath, and
once we finish that one, we'll go back to main . We could continue with this example,
but you probably get the idea by now.
The idea of representing each method call as a piece of paper and putting each one
on top of the others as it is called is a metaphor for Java's call stack.
Call Stack
The internal structure that keeps track of the sequence of methods that have
been called.
If you envision the call stack as a stack of papers with the most recently called
method on top, you'll have a pretty good idea of how it works.
Let's use the idea of the call stack to understand how the recursive file-reversing
method works. To visualize the call stack, we need to put the method definition on a
piece of paper:
public static void reverse(Scanner input) {
if (input.hasNextLine()) {
String line = input.nextLine();
reverse(input);
System.out.println(line);
}
}
line
Notice that the paper includes a place to store the value of the local variable line .
This is an important detail.
 
Search WWH ::




Custom Search