2015年8月16日 星期日

java Pass by-value or Pass by-reference


static void doubleNumber (int input1, intClass input2)
{input1=input1*2; input2.number=input2.number*2;}


In general, there are two ways that a computer language can pass an argument to a subroutine. The first way is pass-by-value. 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.

The second way an argument can be passed is pass-by-reference. In this method, a reference to an argument (not the value of the argument) is passed to the parameter. Inside the subroutine, this reference is used to access the actual argument specified in the call. This means that changes made to the parameter will affect the argument used to call the subroutine.

As you will see, Java uses both approaches, depending upon what is passed.

In Java, when you pass a primitive / simple 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.

When you pass an object to a method, the situation changes dramatically. because objects are passed by reference. Keep in mind that when you create a variable of a class type, you are only creating a reference to an object. Thus , when you pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument. This effectively means that objects are passed to methods by use of call-by--reference. Changes to the object inside the method do affect the object used as an argument.




沒有留言:

張貼留言