call by reference
class Operation{
int data=50;
void change(int data){
data=data+100;//changes will be in the local variable only
}
public static void main(String args[]){
Operation op=new Operation();
System.out.println("before change "+op.data);
op.change(500);
System.out.println("after change "+op.data);
}
}
class Operation2{
int data=50;
void change(Operation2 op){
op.data=op.data+100;//changes will be in the instance variable
}
public static void main(String args[]){
Operation2 op=new Operation2();
System.out.println("before change "+op.data);
op.change(op);//passing object
System.out.println("after change "+op.data);
}
}
Java Call by Reference Example
Below is an example program given, uses call by reference method, to pass
argument/parameter to the method in Java:
/* Java Program Example - Java Argument Passing
* Objects are passed through their reference */
class Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
/* pass an object */
void meth(Test o)
{
o.a = o.a * 2;
o.b = o.b / 2;
}
}
public class JavaProgram
{
public static void main(String args[])
{
Test obj = new Test(150, 200);
int a = 150, b = 200;
System.out.println("The value of obj.a and obj.b before call
:");
System.out.println("obj.a = " + obj.a + "\t obj.b = " + obj.b);
obj.meth(obj);
System.out.println("\nThe value of obj.a and obj.b after call :
");
System.out.println("obj.a = " + obj.a + "\t obj.b = " + obj.b);
}
}
When the above Java program is compile and executed, it will produce the
following output:
Write a java program based on call by value and call by reference
class Operation
int data=50; //instance variable
void change(int data)//passing primitive type as an argument
data=data+100;//changes will be in the local variable only
void change(Operation op1)//passing reference i.e object as an argument
op1.data=op1.data+100;//changes will be in the instance variable
public static void main(String args[]){
Operation op=new Operation();
//call by value
System.out.println("before change "+op.data);
op.change(500);
System.out.println("after change "+op.data);
//call by reference
System.out.println("before change "+op.data);
op.change(op);//passing object
System.out.println("after change "+op.data);