Stack Step By Step

The Stack Step By Step

Start

public static void main(String[] args) 
{
  int i=1; 

  i = silly(i);
} 

int silly(int locali)
{
  locali = 3;
  return locali;
}
  • The stack isn’t really empty, other applications are running but as far as this application is concerned there is only an empty stack
simple java stack

Program starts

public static void main(String[] args) 
{
  int i=1; 

  i = silly(i);
} 

int silly(int locali)
{
  locali = 3;
  return locali;
}
  • main() frame added to stack
simple java stack

Variable created

public static void main(String[] args) 
{
  int i=1; 

  i = silly(i);
} 

int silly(int locali)
{
  locali = 3;
  return locali;
}
  • i variable created in the main() frame
simple java stack

Method call

public static void main(String[] args) 
{
  int i=1; 

  i = silly(i);
} 

int silly(int locali)
{
  locali = 3;
  return locali;
}
  • (Two steps) silly() frame added to stack, locali variable created with a value passed in from main()
simple java stack

Variable set

public static void main(String[] args) 
{
  int i=1; 

  i = silly(i);
} 

int silly(int locali)
{
  locali = 3;
  return locali;
}
  • locali value in silly() changed to 3
simple java stack

Value returned

public static void main(String[] args) 
{
  int i=1; 

  i = silly(i);
} 

int silly(int locali)
{
  locali = 3;
  return locali;
}
  • locali value in silly() returned to main() and stored in i
simple java stack

silly() exits

public static void main(String[] args) 
{
  int i=1; 

  i = silly(i);
}

int silly(int locali)
{
  locali = 3;
  return locali;
}
  • silly() frame deleted as method exits
simple java stack

Main finishes and program closes

public static void main(String[] args) 
{
  int i=1; 

  i = silly(i);
} 

int silly(int locali)
{
  locali = 3;
  return locali;
}
  • main() frame deleted as method exits
simple java stack