Call By Value in Java

Java supports only call by value. It does not support Call By Reference. i.e. If you change the reference of an Object in the called method , then it would not reflect the changes in the method from where it is called.

Let us take an example to understand this. Below is a demo program which explains in which scenario the value changes and in which scenario change will not reflect.

package com.mathapachi;

public class CallByValueInJava {

	private int data = 0;
	CallByValueInJava(int data){
		this.data = data;
	}
	public static void main(String[] args) {
	      CallByValueInJava obj = new CallByValueInJava(100);
              System.out.println("Value of Data Before Method Call = "+obj.data);
              changeData(obj); 
              System.out.println("Value of Data After Method Call = "+obj.data);
	}
	
	private static void changeData(CallByValueInJava obj) {
             obj.data = 200;
              //changing the reference of obj of CallByValueInJava
             obj = new CallByValueInJava(900);
	}

}

Output of the above program is as below:

Value of Data Before Method Call = 100
Value of Data After Method Call = 200

In the method changeData(), before changing the reference of obj we have changed the value of data to 200. Thereafter , we changed the reference to point to a new object. Had Call By Reference been there in Java, then obj would have pointed to the new object address which is not the case and this is confirmed by the output which we get after running the program. The output of 200 shows that the called method changes with respect to reference does not reflect in the method from where it is called.

So, Java Supports only Call By Value and Not Call By Reference.

Sample Demo program for Call by Value with respect to Primitive Data Type:

package com.mathapachi;

public class CallByValueInJava {

	public static void main(String[] args) {
            int data = 50;
            System.out.println("Value of Data Before Method Call = "+data);
            changeData(data); 
            System.out.println("Value of Data After Method Call = "+data);
		 
	}
	
	private static void changeData(int data) {
		data = data + 100;
	}

}

Output of the above program is as below:

Value of Data Before Method Call = 50
Value of Data After Method Call = 50

The above program also indicates that Java supports only Call By Value as the value of data in the above program did not change.