CS 1713: Parameter Passing

Parameter passing and object parameters

Exercise: The Counter class of Case Study 4 has increment and decrement methods. What happens when the following statements are executed?
   Counter c = new Counter();
   printAndIncrement(c);
   System.out.println("After the call, c is " + c);
The printAndIncrement method is:
   public static void printAndIncrement(Counter count) {
      System.out.println("The counter had value " + count);
      count.increment();
      System.out.println("The counter has value " + count);
   }
Ans: After the return from the printAndIncrement method, c has a value of 1. Draw a careful picture tracing what happens.

Compare the above program with the following. What output is generated?

   public static void main(String[] args) {
   int c = 0;
   printAndIncrement(c);
   System.out.println("After the call, c is " + c);
   }

   public static void printAndIncrement(int count) {
      System.out.println("The counter had value " + count);
      count = count + 1;
      System.out.println("The counter has value " + count);
   }
Ans: The method shows that the value is incremented, but the print statement in main shows that its variable c is unchanged. Draw a careful picture tracing what happens.

You can run the Java Simulator to illustrate this example here and here.