Call by value & call by reference:
Whenever we want to just use the values which are
available in the object memory location without disturbing them, then we should
use call by value function.
Whenever we want to directly do the operations in
the original object memory location then we should use call by reference
function.
Note:
Whenever we use call by value then it will store
the values in new memory and do the operation, so it will not affect the
original object memory location.
Whenever we use call by reference then it will
create new reference to the same object memory, so any operations performed
using this new reference will affect the same original object memory location.
Develop a java program which describes
call by value & call by reference concept
package pack1;
public class byvalref {
public void swap(int a,int b) {
int c=a;
b=a;
a=c;
}
public void swap(byvalref ref) {
int c=ref.i;
ref.i=ref.j;
ref.j=c;
}
public static void main(String[] args) {
byvalref
ref1=new byvalref();
System.out.println("before swap i & j are:"+ref1.i+"---"+ref1.j);
ref1.swap(ref1.i,ref1.j);
System.out.println("after swaping i & j using call by value
are:"+ref1.i+"---"+ref1.j);
ref1.swap(ref1);
System.out.println("after swaping i & j using call by ref
are:"+ref1.i+"---"+ref1.j);
} }
No comments:
Post a Comment