Tuesday, 20 December 2011

08 - Parameter passing techniques

//Demonstrating parameter passing techniques

/*
    In java there are two types of parameter passing techniques. They are
    1) Call-by-value
    2) Call-by-reference

    When we pass paramters to methods, all primitive types like int, float, double, byte etc
    are called-by-value and the objetcs are called-by-reference.
*/

class SwapIt
{
    int a;
    int b;
   
    void swap(int x,int y)
    {
        int temp = x;
        x = y;
        y = x;
    }

    void swap(SwapIt s)
    {
        int temp = s.a;
        s.a = s.b;
        s.b = temp;
    }
}

class SwapDemo
{
    public static void main(String args[])
    {
        SwapIt obj = new SwapIt();
        int i=10,j=20;
        System.out.println("Values of i and j before swapping are: "+i+","+j);
        obj.swap(i,j);
        System.out.println("Values of i and j after swapping are: "+i+","+j);
        obj.a = 10;
        obj.b = 20;
        System.out.println("Values of a and b before swapping are: "+obj.a+","+obj.b);
        obj.swap(obj);
        System.out.println("Values of a and b after swapping are: "+obj.a+","+obj.b);
    }
}

Download the program only: http://paste2.org/followup/1832520

2 comments: