Tuesday 11 October 2016

Java Pass By Value and Pass By Reference


 Java Pass By Value and Pass By  Reference 




Pass by Value


In java we have a pass by value, when we use primitive type as parameters then it is a pass by value. Thus, what occurs to the parameter that receives the argument has no affect outside the method.
This method is copy of the passed-in variable is copied into the argument. Any changes to the argument do not affect the original one.
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 java we use the reference type as parameters in a method then it become a pass by value for the reference value. The reference type refer to an object, so when we use the reference data type as a parameter, a copy of the reference value is made available to the invoked method, which enables the invoked method to work on the same object as the one reference by the invoking method.

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 .


We have a method defined as follows:

 public void method(Account ac,int i)
 {
i+=100;
ac.deposit(10000);
i+=100;

ac = new CurrentAccount
  (1005, “tom”,4000);

i+=100;
ac.deposit(3000);
 }


This method is beging used from another code as follows:


1 Account ac = 
   new CurrentAccount(1005, “tom”, 2000);

2 int a = 100;

3 ac.deposit(3000);

4 method(ac,a);

5 System.out.println
   (ac.getBalance()+”, “+a);

It prints “15000, 100”


Since primitive types are pass by value, the value of a is unchanged. In line 1, balance in Account(ac) is 2000, in line 3 balance in ac 5000. Now the reference to ac is copied to the parameter ac in method, so ac in method refers to the same object ac which is declared in line 1. In line 7, the balance would be 15000, now line 9 makes ac in the method ac in method refer to a new object, so the object refered by ac in line 1 is unaffected. line 9 would make the method loose the reference to the object which was passed as a parameter in line 4.
Example:

class A
{
void print(int i) 
        //pass by value
{
System.out.println(i);
}
public String toString()
{
return "Class A";
}
void toPrint(A obj) 
        //pass by reference
{
System.out.println(obj);
}
}
class B extends A
{
public static void main(String[] str)
{
B obj = new B();
obj.print(5); 
                //pass by value
obj.toPrint(new B()); 
                //pass by reference
}
}






Searches related to java Pass By Value and Pass By Reference

No comments:
Write comments

Labels

ADVERTISEMENT