Swap Program demonstrating Call by Reference in Java

In Java When a simple type is passed to a method, it is done by use of call-by-value. Objects are passed by use of call-by-reference.

//Program demonstrating Call by Reference in Java

SwapCallByRefDemo.java

class Test

{

                int a, b;

                Test(int i, int j)

                {

                                a=i;

                                b=j;

                }

                void swap(Test ob)

                {

                                int c;

                                c=ob.a;

                                ob.a=ob.b;

                                ob.b=c;

                                System.out.println(“Inside swap method”);

                                System.out.println(“a = “+ob.a+” b = “+ob.b);

                }

}

class SwapCallByRefDemo

{

                public static void main(String[] args)

                {

                                Test ob = new Test(2,3);

                                System.out.println(“Before Swapping”);

                                System.out.println(“ob.a = “+ob.a+” ob.b = “+ob.b);

                                ob.swap(ob);

                                System.out.println(“After Swapping in main method”);

                                System.out.println(“ob.a = “+ob.a+” ob.b = “+ob.b);

                }

}


Advertisements

2 thoughts on “Swap Program demonstrating Call by Reference in Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s