A Closer Look at Argument Passing
In general, there arc two ways that a computer language can pass an argument to a
subroutine. The first way is call-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 used to call it. The second Mayan argument can be passed Is cancer. In this method, a reference to an argument (not the value of the argument 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 methods, depending upon what is passed. In Java, when you pass a 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. For example, consider the following program:
As you can see, the operations that occur inside meth I'have no effect on the values of' a and b used in the call; their values here did not change to 30 and 10. 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. Th~ 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. For example, consider the following pogrom.
As you can see! in this case, the actions inside helm have affected the object used as an argument. As a point of interest, when an object reference is passed to a method, the referee self is passed by use of call-by-value. However, since the value being passe d refers object, the copy of that value will still refer to the same object that its corresponding argument docs.
As you can see, each time is invoked, a new object is created, and a reference to it is returned to the calling routine.The. preceding program makes another important point: Since all objects are dynamically allocated using new, you don't need to worry about an object going out-of-scope because the method in which it was-created terminates. The object will continue to exist as long as there is a reference to it somewhere in your program. When there are no references to it, the object will be reclaimed the next time garbage collection takes place.