JMU
Parameter Passing Mechanisms
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Common Parameter Passing Mechanisms
Parameter Passing in Java
Passing Value Types

Trying to Swap Two Values

javaexamples/basics/ParameterPassingExample1.java (Fragment: 0)
    /**
     * This function will only swap the local copies
     * of the parameters a and b
     */
    public static void swapNot(int a, int b)
    {
        int temp;


        temp = a;
        a    = b;
        b    = temp;
    }
        
Parameter Reference Types (cont.)

Swapping the Attributes of Two Objects

javaexamples/basics/Pair.java (Fragment: 0)
public class Pair
{
    public int  a, b;
}
        
javaexamples/basics/ParameterPassingExample1.java (Fragment: 1)
    /** This function will swap the values of
     *  the instance variables a and b in the object p
     */
    public static void swapAttributes(Pair p)
    {
        int temp;


        temp = p.a;
        p.a  = p.b;
        p.b  = temp;
    }
        
Parameter Reference Types (cont.)

Trying to Swap Two Objects

javaexamples/basics/Pair.java (Fragment: 0)
public class Pair
{
    public int  a, b;
}
        
javaexamples/basics/ParameterPassingExample1.java (Fragment: 2)
    /** This method will only swap the local copies
     *  of the references to m and n
     */
    public static void swapNotObject(Pair m, Pair n)
    {
        Pair temp;


        temp = m;
        m    = n;
        n    = temp;
    }
        
Parameter Reference Types (cont.)

Swapping Two Elements of an Array

javaexamples/basics/ParameterPassingExample1.java (Fragment: 3)
    /** This function will swap the values of
     *  elements 0 and 1 of the array data
     */
    public static void swapElements(int[] data)
    {
        int temp;


        temp    = data[0];
        data[0] = data[1];
        data[1] = temp;
    }
        
Parameter Reference Types (cont.)

Trying to Swap Two Arrays

javaexamples/basics/ParameterPassingExample1.java (Fragment: 4)
    /** This method will only swap the local copies
     *  of the references to the arrays m and n
     */
    public static void swapNotArrays(int[] m, int[] n)
    {
        int[] temp;


        temp = m;
        m    = n;
        n    = temp;
    }