Call By Value
Definition: It is a type of function call wherein the argument passed is of a primitive data type and the value of the argument gets copied to the parameter of the function and in the function definition even if we are swapping the values of the parameter we are actually swapping the copies of the argument not the actual argument.
Example
Call By Reference
Definition: The argument passed in this type of function is an object type and not a primitive data type. Using call by reference the modifications can be done on the actual arguments because the references of the arguments are passed during the function call.
Example
Definition: It is a type of function call wherein the argument passed is of a primitive data type and the value of the argument gets copied to the parameter of the function and in the function definition even if we are swapping the values of the parameter we are actually swapping the copies of the argument not the actual argument.
Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Test | |
{ | |
int x=10; | |
int y=20; | |
void swap(int a,int b) | |
{ | |
int temp; | |
temp=a; | |
a=b; | |
b=temp; | |
} | |
} | |
public class TestMain | |
{ | |
public static void main(String[] args) | |
{ | |
A obj=new A(); | |
int t=10; | |
int s=20; | |
obj.swap(t, s); | |
System.out.println(t+" "+s);// The argument value remains the same | |
//it is not changed. | |
} | |
} |
Call By Reference
Definition: The argument passed in this type of function is an object type and not a primitive data type. Using call by reference the modifications can be done on the actual arguments because the references of the arguments are passed during the function call.
Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Test | |
{ | |
int i,j; //Instance variables for Class Test | |
void swap_ref(Test a, Test b) | |
{ | |
int temp; | |
temp = a.i; | |
a.i = b.i; | |
b.i = temp; | |
temp = a.j; | |
a.j = b.j; | |
b.j = temp; | |
} | |
} | |
public class TestMain | |
{ | |
public static void main(String[] args) | |
{ | |
Test t2 = new Test(); | |
Test t3 = new Test(); | |
t2.i= 10; //Initialising the instance value of class Test with objects t2 and t3 | |
t2.j = 20; | |
t3.i = 5; | |
t3.j = 7; | |
t1.swap_ref(t2, t3); | |
} | |
} |
For details regarding Online Java J2ee Training please visit www.javatutoronline.com