A reference stored in a passed variable cannot be replaced with a different reference inside the method body.
This means that if a variable x stores a reference to an object ob, passing x into a method cannot cause x to point to a different object. The reference in x cannot be replaced with a different reference simply by passing x into a method. This is because when a variable x is passed, only a copy of x is passed, so pointing that copy to a different object (from within some method) will not affect x.
What is the output of the following code?
Example 1
public class CallByValue {
int data = 50;
int originalValue;
void change(int data) {
//this.data = data + 100 // change will be reflected in object
data = data + 100;//changes will be in the local variable only
}
void callByValue(CallByValue copy){
//creates a new object
copy = new CallByValue();
copy.originalValue = 2000;
}
}
public class Main {
public static void main(String args[]) {
System.out.println("call by value in passing primitive value.......");
CallByValue ob = new CallByValue();
System.out.println("before change " + ob.data); //50
ob.change(500); // passing a value
System.out.println("after change " + ob.data); //50
System.out.println("call by value in passing object reference.......");
CallByValue ob1 = new CallByValue();
ob1.originalValue = 1000;
//sending a copy of reference but it is call by value
ob1.callByValue(ob1);
// 1000 not 2000 since change in copy does not affect to the original value
System.out.println("after change " + ob1.originalValue); //1000
}
}
Example 2: use of "this" with call-by-value
public class JavaExample {
int x = 10;
int y = 20;
void display(JavaExample A, JavaExample B){
A.x = 95;
B.y = 55;
System.out.println("x = " + x);
System.out.println("y = " + y);
//System.out.println("x = " + A.x); what happens?
//System.out.println("x = " + A.x); what happens?
}
public static void main(String[] args) {
JavaExample C= new JavaExample();
JavaExample D = new JavaExample();
D.y = 55;
C.display(C, D); // x = 95, y = 20
D.display(C, D); // x = 10, y = 55
}
}