Java2all.com  

Call by value





Share This Topic -

Now we all know that how to define and call the methods.

There are two types of calling method and those are

1. call by value

2. call by reference

Here we illustrate call by  value and in next topic we will look at call by reference.

In call by value when we call any method we pass value as method parameter so changing in local variables of the method doesn't`t affect the original variables of class.

This method copies the value of an argument into the formal parameter of the subroutine.

Therefore, changes made to the parameter of the subroutine have no effect on the argument.

In java, when we pass a primitive type to a method, it is passed by value.

Thus, what occurs to the parameter that receives the argument has no effect outside the method.

EX :

 public class CallBy_Value 
{
	public static void main(String[] args)
	{
		Value v = new Value(10,20);
		System.out.println("a and b before call............");
		System.out.println("a = "+v.a);
		System.out.println("b = "+v.b);
		v.call(v.a,v.b);		// CALL BY VALUE
		System.out.println("a and b after call............");
		System.out.println("a = "+v.a);
		System.out.println("b = "+v.b);
	}
}

class Value
{
	int a,b;
	Value(int i,int j)
	{
		a = i ;
		b = j;
	}
	void call(int a, int b)
	{
		a = a * 2;
		b = b * 2;
	}
}

 
Output :
 
a and b before call............
a = 10
b = 20
a and b after call............
a = 10
b = 20
 
You can see that after calling method we change value of a and b but it will not afect the original value of class` members because of call by value.
 
We pass value v.a and v.b as parameter and it will change local method`s a and b variables.