Answers to Self-Study Questions

Test Yourself #1

When the program executes, this is printed:

  10
  Ann
This is because the assignment P.age = 10 in method changePerson modifies the age field of the object in the heap pointed to by its Person parameter, which is the same object pointed to by variable P in main.

However, the modification to the name field has no effect on the Person pointed to by main's P, because when that statement is executed, formal parameter P has already been set to point to a different Person object.


Test Yourself #2

Here are pictures assuming that parameters are passed by value. Only the space for parameters and local variables is shown for the ARs.

Stack when swap is first called:

       +====+
    y: | 20 |
       +----+
    x: | 10 |
       +====+        +-------------------+
    A: |  ---------> | 10 | 20 | 30 | 40 |
       +====+        +-------------------+
Stack just before swap returns:
       +====+
    y: | 10 |
       +----+
    x: | 20 |
       +====+        +-------------------+
    A: |  ---------> | 10 | 20 | 30 | 40 |
       +====+        +-------------------+
Here are pictures assuming that parameters are passed by reference. Only the space for parameters and local variables is shown for the ARs.

Stack when swap is first called:

       +====+
    y: | -------------------+
       +----+               |
    x: | --------------+    |
       +====+          v    v
    A: |  ---------> +-------------------+
       +====+        | 10 | 20 | 30 | 40 |
		     +-------------------+
Stack just before swap returns:
       +====+
    y: | -------------------+
       +----+               |
    x: | --------------+    |
       +====+          v    v
    A: |  ---------> +-------------------+
       +====+        | 20 | 10 | 30 | 40 |
		     +-------------------+

Test Yourself #3

Test Yourself #3: One way the caller can implement it is as follows.

la $t0 _x		# Load address of _x into T0
sw $t0 0($sp)		
subu $sp $sp 4		# Move stack pointer 
lw $t0 _y		# Load value of _y into T0
sw $t0 0($sp)
subu $sp $sp 4 # Move stack pointer