University of Toronto - Fall 2000
Department of Computer Science

Week 2 - Return Values

Program Example

We're currently using printCopies(), which wasn't part of our original list of methods. Is there another way to print the number of copies?

	class Book {
		private int numCopies;

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

		public void checkOut() {
			numCopies = numCopies - 1;
		}

		public int numCopies () {
		  	return numCopies;
		}
	}

	public class Library {
		public static void main(String[] args) {
			Book b1 = new Book();
			b1.buyCopies(5);
			b1.checkOut();
			System.out.println (b1.numCopies());
		}
	}
What would the output be?
	4

What if we wanted the output to be ...
         Copies: 4

The return statement has three effects:

  1. The value of the expression is calculated (numCopies in this case)
  2. That value is given back to the statement that called the method (the statement in main() in this case)
  3. The execution of the method containing the return stops right away. (any code after the return in the method is ignored.)

Memory Model