University of Toronto - Fall 2000
Department of Computer Science

Week 2 - Memory Model

A variable can only have one value

Program Example

	/**
 	* Book models the behaviour of a book
 	*/
	class Book {

		private int numCopies;

		public void buyCopies (int copies) {
			numCopies = copies;
		}

		public void printNumCopies () {
		  	System.out.println("Copies: " + numCopies);
		}
	}

	public class Library {

		public static void main(String[] args) {
			Book b1 = new Book();
			b1.buyCopies(5);
			b1.printCopies();
			b1.buyCopies(2);
			b1.printCopies();
		}
	}

What would the output be?

	Copies: 5

	Copies: 2   (not 7)

The variable numCopies can only hold one value at a time, and when you call the method buyCopies with 2 as the argument, it overwrites the old value in numCopies.

Memory Model

This is what the diagram looks like after executing statement 1 in the main method. We'll discuss how to update this diagram during the lectures.


System.out.println

You are not responsible for this, but here is a complete memory model diagram that shows all of the objects that would actually exist. The PrintStream object is needed in order to show how System.out.println is modelled. We would not ask you to model System.out.println for this course.