Download ParamPassingDemo.java
1: /** This class demonstrates parameter passing in Java. 2: * Here a primitive (int) and an object (Person) are passed to aMethod. 3: * The results show that num is unchanged as a result of the method call 4: * but the object "wayne" had it's name property changed. 5: * 6: * This happens because Java uses "pass by copy" (or "pass by value"). 7: * That means the "actual" parameters in the method call are copied into 8: * "formal" parameters, which are distinct variables. So changing "i" has 9: * no effect on "num". 10: * 11: * With objects, remember that it is *not* the object that is passed and 12: * copied, is is merely a reference to it. So if aMethod were to change "p", 13: * that would have no effect on "wayne", but if aMethod were to change the 14: * object's properties that both "p" and "wayne" refer to, than that only 15: * object's properties are changed at that point, and the change persists 16: * even after the method call is finished. 17: * 18: * Written 2004 by Wayne Pollock, Tampa Florida USA. 19: */ 20: 21: public class ParamPassingDemo 22: { 23: static void aMethod ( Person p, int i ) 24: { p.name = "Hymie Piffl"; 25: ++i; 26: } 27: 28: public static void main (String [] args ) 29: { 30: Person wayne = new Person( "Wayne Pollock" ); 31: int num = 2; 32: 33: System.out.println( "Before invoking aMethod(Person,int):\n" ); 34: System.out.println( "\twayne.name = \"" + wayne.name + "\"" ); 35: System.out.println( "\tnum = " + num ); 36: 37: aMethod( wayne, num ); 38: 39: System.out.println( "\nAfter invoking aMethod(Person,int):\n" ); 40: System.out.println( "\twayne.name = \"" + wayne.name + "\"" ); 41: System.out.println( "\tnum = " + num ); 42: } 43: } 44: 45: class Person 46: { 47: String name; 48: 49: // Person constructor: 50: public Person ( String name ) 51: { 52: this.name = name; 53: } 54: 55: // Rest of class Person goes here 56: }