The Runtime Stack


An example without objects

 

 
What is the runtime stack?

 

Consider this example

public class RuntimeExample {

    public static void main (String[] argv)
    {
	// 1.  
	methodA ();
	// 7. 
    }

    static void methodA ()
    {
	int i = 5;
	// 2.
	methodB (i);
	// 6.
    }

    static void methodB (int k)
    {
	int j = 7;
	k ++;
	// 3.
	methodC (k, j+1);
	k ++;
	// 5.
    }

    static void methodC (int a, int b)
    {
	// 4.
	System.out.println (a + b);
    }

}
 
Exercise 1: Without implementing, mentally execute the above program and determine what gets printed out.
 

Let's now draw the stack at each of the moments numbered 1 to 7 above.

 


An example with objects

 

Consider this example

class ObjX {

    int methodA (int k)
    {
	return methodB (k, k+1);
    }

    int methodB (int a, int b)
    {
	return (a + b);
    }

}

public class RuntimeExample2 {

    public static void main (String[] argv)
    {
	ObjX x = new ObjX ();
	int d = x.methodA (5);

	ObjX x2 = new ObjX ();
	d = d + methodC (x2);
	System.out.println (d);
    }

    static int methodC (ObjX y)
    {
	int z = y.methodA (6);
	return z + 1;
    }

}
 
Exercise 2: Without implementing, mentally execute the above program and determine what gets printed out.
 
Exercise 3: Draw the various stages in the evolution of the stack. That is, draw the state of the runtime stack each time a new stack record is created or removed.