posted 19 years ago
Hi Arun,
Where did you hear all this stuff about creating a stack from a program? I want you to forget it, all of it, because it's simply wrong. Forgotten? Good; now I'll explain it the right way.
The Java virtual machine, like many real computers, does use a stack to keep track of a running program (actually, one for each thread). There is no stack at all until a program starts to run. The stack reflects the current program state, and contains no information at all about other parts of the program that are not running.
At the top of the stack there is always a pile of data (called a "stack frame") which describes the currently running method. When method A calls method B, a new stack frame is pushed on top of the stack. If B calls C, then another frame is pushed on, so the stack has three frames on it: C, B, A, top to bottom. When C returns, its frame is removed, revealing the one for B. When B returns, its frame is removed, revealing A. Now if A calls another method D, a new frame for D is put right on top of A's frame.
So you see, in your example, first a frame for main is created, and then a frame for showData is pushed onto the stack. Then showData returns and its frame is removed, leaving main exposed again. Then main calls setData, and a new frame for setData is pushed, which is then removed when setData returns.