ParamPassingDemo.java

Download ParamPassingDemo source file

/** This class demonstrates parameter passing in Java.
  * Here a primitive (int) and an object (Person) are passed to aMethod.
  * The results show that num is unchanged as a result of the method call
  * but the object "wayne" had it's name property changed.
  *
  * This happens because Java uses "pass by copy" (or "pass by value").
  * That means the "actual" parameters in the method call are copied into
  * "formal" parameters, which are distinct variables.  So changing "i" has
  * no effect on "num".
  *
  * With objects, remember that it is *not* the object that is passed and
  * copied, is is merely a reference to it.  So if aMethod were to change "p",
  * that would have no effect on "wayne", but if aMethod were to change the
  * object's properties that both "p" and "wayne" refer to, than that only
  * object's properties are changed at that point, and the change persists
  * even after the method call is finished.
  *
  * Written 2004 by Wayne Pollock, Tampa Florida USA.
  */

public class ParamPassingDemo
{
   static void aMethod ( Person p, int i )
   {  p.name = "Hymie Piffl";
      ++i;
   }

   public static void main (String [] args )
   {
        Person wayne = new Person( "Wayne Pollock" );
        int num = 2;

        System.out.println( "Before invoking aMethod(Person,int):\n" );
        System.out.println( "\twayne.name = \"" + wayne.name + "\"" );
        System.out.println( "\tnum = " + num );

        aMethod( wayne, num );

        System.out.println( "\nAfter invoking aMethod(Person,int):\n" );
        System.out.println( "\twayne.name = \"" + wayne.name + "\"" );
        System.out.println( "\tnum = " + num );
   }
}

class Person
{
   String name;

   // Person constructor:
   public Person ( String name )
   {
      this.name = name;
   }

   // Rest of class Person goes here
}