Memory Lab

Memory Diagrams

Introduction

Take a moment to trace the Java code listed below. (The Point class here is the same class we worked with in last week’s lab.)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
    public static void mover(Point p) {
        double curX = p.getX();
        p.setX(curX + 1.0);
    }

    public static void main(String[] args) {
        int count = 7;
        int[] nums = {1, 2, 3}
        Point p1 = new Point(1.0, 4.0);
        
        mover(p1);
    }

Here is a memory diagram illustrating the contents of memory just before the call to mover returns:

Memory Diagram

The two boxes labeled main and mover are referred to as activation records. They represent the region of memory where the local variables (including parameters) associated with a single method call are stored. The area of memory reserved for activation records is referred to as the stack or the call stack. Each activation record disappears when its associated method returns.

The right side of the diagram represents the heap. The heap is where objects are stored in memory. Basically, anything instantiated using the new keyword is created on the heap.

Java Tutor

Java Tutor is a tool that can be used to visualize the contents of memory during the execution of a Java program. Use Java Tutor to trace the execution of the code above. Make sure you understand what’s happening each time you take a step in the program:

More Complicated Example

Draw the contents of memory just before the following main method exits. Use a sheet of paper and show your work to your group members. Make sure that you all agree on the final diagram and on the expected output for this code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
    public static void copier(Pointt[] points, Pointt pointA) {
        for (int i = 0; i < points.length; i++) {
            points[i] = pointA;
        }
    }
    
    public static void main(String[] args) {
        
        Pointt pointZero = new Pointt(0.0, 0.0);
        Pointt[] threePoints = new Pointt[3];
        Pointt[] others = threePoints;
        
        copier(threePoints, pointZero);
        
        threePoints[0].setX(1.0);
        
        System.out.println(threePoints[1].getX());
        
        System.out.println(pointZero.getX());
        
        System.out.println(others[0].getX());
    }

Once you are confident in your answer, use Java Tutor to double check your work. (The class name has been changed to Pointt here to prevent Java Tutor from complaining about using a reserved name.)

Canvas Quiz

Complete the Canvas quiz associated with today’s activity. You’ll have as many attempts as you need, and you are welcome to discuss your answers with your group members and to ask for help if you need it.

Last modified April 30, 2022: practice coding exam (a2ce8c8)