Call by reference :
Here we pass reference as parameter in function calling.
We all know that reference means object so we pass object as parameter.
A reference to an argument (not value of argument) is passed to the parameter.
Inside the subroutine, this reference is used to access the actual argument specified in the call.
This means that changes made to the parameters will affect the argument used to call the subroutine.
When we pass an object to a method, the situation changes, because objects are passed by call-by-reference.
When we create a variable of a class type, we are only creating a reference to an object. Thus,
When you pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument.
This effectively means that objects are passed to method do affect the object used as an argument.
EX :
public class CallBy_Reference
{
public static void main(String[] args)
{
Reference r = new Reference(10,20);
System.out.println("a and b before call............");
System.out.println("a = "+r.a);
System.out.println("b = "+r.b);
r.call(r); // CALL BY REFERENCE
System.out.println("a and b after call.............");
System.out.println("a = "+r.a);
System.out.println("b = "+r.b);
}
}
class Reference
{
int a,b;
Reference(int i,int j)
{
a = i ;
b = j;
}
void call(Reference r)
{
r.a = a * 2;
r.b = b * 2;
}
}
Output :
a and b before call............
a = 10
b = 20
a and b after call.............
a = 20
b = 40
You can see that after calling method value of original a and b is changed because of call by reference.
Here we pass "r" reference (Object) as parameter in method calling. So changes inside method will affect original variable of class.
I have read your blog its very attractive and impressive. I like it your blog.
ReplyDeleteBest BCA Colleges in Noida