• Post Reply Bookmark Topic Watch Topic
  • New Topic

stack(storing of function)  RSS feed

 
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear sir as we knoe that like see

public class first{
public void showData(){}
public void setData(){}
public static void main(String[] args){
first p=new first();
p.showData();
p.setData();



}
}

for this program a stack will created to store the method so
so in stack at
0 position main method will store isn't it.
1 position showData will store isn't it.
2 position setdata will stored isn't it.

now as we know that execution of program start from main method but on the other hand stack is based on FILO rules then how JVM will call main method first to load program it should be called at last time because main method has gon in stack at first time.
And one thing more that i would like to know that and if i will call method first setData then showData like
p.setData();
p.showData();

then at 1 postion setData will sttored is it true?

with regard
Arun kumar maalik
 
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Arun Maalik
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks sir
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!