Java Pass By Value and Pass By Reference

Java Pass By Value and Pass By Reference

Java uses pass by value. There is no pass by reference in Java. 

This Java tutorial is to walk you through the difference between pass by value and pass by reference, 

then explore on how Java uses pass by value with examples. 

Most importantly we need to be clear on what we mean by using the terminology “pass by value” and “pass by reference”. 

Some people are saying that in Java primitives are passed by value and objects are passed by reference. 

It is not correct.

Pass by Value

Let us understand what is pass by value. Actual parameter expressions that are passed to a method are evaluated and a value is derived. 

Then this value is stored in a location and then it becomes the formal parameter to the invoked method. 

This mechanism is called pass by value and Java uses it.

Pass by Reference

In pass by reference, the formal parameter is just an alias to the actual parameter. 

It refers to the actual argument. Any changes done to the formal argument will reflect in actual argument and vice versa.

Java Language Specification Says

In Java Language Specification 8.4.1. Formal Parameters section it is stated that,

“When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables, each of the declared type, before execution of the body of the method or constructor.”

It is clearly evident that the actual argument expressions are evaluated and values given to the method body as formal parameters. 

When an object is passed as argument, that object itself is not passed as argument to the invoked method. 

Internally that object’s reference is passed as value and it becomes the formal parameter in the method.

Java uses JVM Stack memory to create the new objects that are formal parameters. 

This newly created objects scope is within the boundary of the method execution. 

Once the method execution is complete, this memory can be reclaimed.

Test Pass by Value vs Pass by Reference

We can run a simple swap test and check for pass by value vs pass by reference. 

Let us pass two arguments and swap them inside the invoked method, 

then check if the actual arguments are swapped. 

If the actual arguments are affected then the mechanism used is pass by reference otherwise it is pass by value.

public class Swap {

	public static void main(String args[]) {
		Animal a1 = new Animal("Lion");
		Animal a2 = new Animal("Crocodile");

		System.out.println("Before Swap:- a1:" + a1 + "; a2:" + a2);
		swap(a1, a2);
		System.out.println("After Swap:- a1:" + a1 + "; a2:" + a2);
	}

	public static void swap(Animal animal1, Animal animal2) {
		Animal temp = new Animal("");
		temp = animal1;
		animal1 = animal2;
		animal2 = temp;
	}

}

class Animal {
	String name;

	public Animal(String name) {
		this.name = name;
	}

	public String toString() {
		return name;
	}
}

Example Output:

Before Swap:- a1:Lion; a2:Crocodile
After Swap:- a1:Lion; a2:Crocodile

Objects are not swapped because Java uses pass by value.

Swap in C++:

Same code will swap the objects in C++ since it uses pass by reference.

void swap(Type& arg1, Type& arg2) {
    Type temp = arg1;
    arg1 = arg2;
    arg2 = temp;
}

Does Java Passes the Reference?

Everything is simple and then why is this topic so hot? 

Now let us look at the following code where we able to change the property of a passed argument object inside a method and it gets reflected in the actual argument.

public class Swap {

	public static void main(String args[]) {
		Animal a = new Animal("Lion");

		System.out.println("Before Modify: " + a);
		modify(a);
		System.out.println("After Modify: " + a);
	}

	public static void modify(Animal animal) {
		animal.setName("Tiger");
	}

}

class Animal {
	String name;

	public Animal(String name) {
		this.name = name;
	}

	public String toString() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

Example Output:

Before Modify: Lion
After Modify: Tiger

If the arguments are passed by value then how we are able to change an attribute of the passed argument? 

This is because Java passes the object reference ‘by value’. 

When an object is passed as argument to a method, actually the reference to that object is passed. 

The formal parameter is a mapping of the reference to the actual parameter.

Java Passes Reference by Value

Following figures explains method scope for variables with respect to call by value. Consider the numbers 100, 200, 600 and 700 as pointers to memory location, these are logical only and for your understanding.



call-by-value-calling-method

In figure 1, there are two objects with variable name a1, a2 which references the location 100 and 200 respectively.

call-by-value-called-method-scope

In figure 2, there are two objects named formal-arg1, formal-arg2 which references location 600 and 700 respectively. 

Here is the catch, contents of the location 600, 700 are again references to another location 100 and 200. 

So the called method has got the reference of the passed arguments. 

Using the reference it can manipulate only the contents of the actual argument object. 

But it cannot change the fact that a1 points to 100 and a2 points to 200, 

that’s what we are trying to do when we swap the objects.

Important point to note is that “the reference is copied as a value” to a new variable and it is given as formal parameter to the called method. 

It does not get a1 variable which is the actual argument in scope. 

This is the key difference between pass by value and pass by reference.


call-by-value-calling-method

In figure 1, there are two objects with variable name a1, a2 which references the location 100 and 200 respectively.

call-by-value-called-method-scope

In figure 2, there are two objects named formal-arg1, formal-arg2 which references location 600 and 700 respectively. 

Here is the catch, contents of the location 600, 700 are again references to another location 100 and 200. 

So the called method has got the reference of the passed arguments. 

Using the reference it can manipulate only the contents of the actual argument object. 

But it cannot change the fact that a1 points to 100 and a2 points to 200, that’s what we are trying to do when we swap the objects.

Important point to note is that “the reference is copied as a value” to a new variable and it is given as formal parameter to the called method. 

It does not get a1 variable which is the actual argument in scope. This is the key difference between pass by value and pass by reference.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值