Skip to main content
Engineering LibreTexts

12.7: Stack Diagrams

  • Page ID
    18102
  • Pulling together the code fragments from the previous section, here is a complete class definition:

    public class PrintTime {
    
        public static void printTime(int hour, int minute) {
            System.out.print(hour);
            System.out.print(":");
            System.out.println(minute);
        }
    
        public static void main(String[] args) {
            int hour = 11;
            int minute = 59;
            printTime(hour, minute);
        }
    }
    

    printTime has two parameters, named hour and minute. And main has two variables, also named hour and minute. Although they have the same names, these variables are not the same. hour in printTime and hour in main refer to different storage locations, and they can have different values.

    For example, you could invoke printTime like this:

    int hour = 11;
    int minute = 59;
    printTime(hour + 1, 0);
    

    Before the method is invoked, Java evaluates the arguments; in this example, the results are 12 and 0. Then it assigns those values to the parameters. Inside printTime, the value of hour is 12, not 11, and the value of minute is 0, not 59. Furthermore, if printTime modifies one of its parameters, that change has no effect on the variables in main.

    One way to keep track of everything is to draw a stack diagram, which is a state diagram (see Section 2.3) that shows method invocations. For each method there is a box called a frame that contains the method’s parameters and variables. The name of the method appears outside the frame; the variables and parameters appear inside.

    Stack diagram for PrintTime.
    Figure \(\PageIndex{1}\): Stack diagram for PrintTime.

    As with state diagrams, stack diagrams show variables and methods at a particular point in time. Figure 4.7.1 is a stack diagram at the beginning of the printTime method.

    • Was this article helpful?