Thursday 10 January 2013

What is call by value and call by reference in java with example?

CALL BY VALUE:  

Look at first example:

class Hello
{

void disp(int i,int j)

{

i*=2;

j/=2;

}

}


class T7

{

public static void main(String as[])

{

int a=99;

int b=77;

System.out.println("before call");
System.out.println("a="+a);

System.out.println("b="+b);


Hello h=new Hello();

h.disp(a,b);

System.out.println("AFTER call");

System.out.println("a="+a);

System.out.println("b="+b);

 }

}


OUTPUT:

before call

a=99

b=77

AFTER call

a=99

b=77


When you pass a simple type to a method, it is passed by value. Thus what occurs to the parameter that receives the argument has no effect outside the method. Here the operation occur inside disp() have no effect on the values of a and b used in the call. Their values didn't change to 198 and 38.

CALL BY REFERENCE:

class Hello
{

int a,b;

Hello(int i,int j)

{

a=i;

b=j;

}

void disp(Hello o) //pass an object

{

o.a*=2;

o.b/=2;

}

}


class T6

{

public static void main(String as[])

{

Hello h=new Hello(15,20);

System.out.println("before call");

System.out.println("a="+h.a);

System.out.println("b="+h.b);

h.disp(h);

System.out.println("AFTER call");

System.out.println("a="+h.a);

System.out.println("b="+h.b);

}

      }

OUTPUT:

before call

a=15

b=20

AFTER call

a=30

b=10


When you pass an object to a method the situation change dramatically. Because objects are passed by Reference. When you creating a variable of a class type ,  you are only creating a reference to an object. change to the object inside the method do effect the object used as an argument. When object reference is passed to a method, the reference itself is passed by use of call-by-value.

2 comments:

  1. It is in reality a great and helpful piece of info. I'm glad that you shared this useful info with us. Please stay us up to date like this. Thanks for sharing.

    ReplyDelete
  2. Normally I do not learn post on blogs, but I would like to say that this write-up very pressured me to check out and do so! Your writing taste has been amazed me. Thanks, quite nice article.

    ReplyDelete