CSC108 Lecture #6 - Passing Parameters


Passing Parameters

Remember that a method gets COPIES of its parameters. It doesn't have access to the actual variable used as the argument -- and in fact the argument isn't always a variable. It might be an expression instead.

Here is an example that shows what happens when different types of values are passed as parameters, and changed within a method.


TestParams.java

public class TestParams {
	public static void main (String[] args) {

		// Example when the string passed as a parameter is changed
		// inside the "m1" method.
		String ptooey = "help!";
	   	System.out.println(ptooey);
	   	m1(ptooey);
	   	System.out.println(ptooey);
	   	System.out.println();

		// Example when the contents of the Num object passed
		// as a parameter is changed inside the "m2" method.
		Num myNum = new Num();
		myNum.setNum (55);
	   	System.out.println(myNum);
	   	m2(myNum);
	   	System.out.println(myNum);
	   	System.out.println();

		// Example when the reference to the Num object passed
		// as a parameter is changed inside the "m3" method.
		myNum = new Num();
		myNum.setNum (99);
	   	System.out.println(myNum);
	   	m3(myNum);
	   	System.out.println(myNum);

        // Example when a primitive type passed
        // as a parameter is changed inside the "m4" method.
        int i = 55;
        System.out.println(i);
        m4(i);
        System.out.println(i);
	}
	
	private static void m1 (String s) {
	   	s = s + "boo!";
	}

	private static void m2 (Num n) {
	   	n.setNum (100);
	}

	private static void m3 (Num n) {
	   	n = new Num();
		n.setNum(66);
	}

    private static void m4 (int j) {
        j = 66;
    }
}

Num.java

class Num {
	private int theNum = 0;
	
	public void setNum (int newVal) {
		theNum = newVal;
	}

	public String toString () {
		return "Num contains: " + theNum;
	}
}

Output for TestParams.java

help!
help!

Num contains: 55
Num contains: 100

Num contains: 99
Num contains: 99

55
55

[ CSC108 Home | Outline | Announcements | Newsgroup | Assignments | Lectures | Marks | Links ]


U of T IMAGE

© Copyright 2000. All Rights Reserved.