Computer Programming I Instructor: Greg ShawCOP 2210 Parameter-Passing in JavaI. Review of TerminologyParameters (aka: Parameter Variables)- Appear in the method heading - Are just “place holders” for the actual values to be usedin the method- Receive the values of the corresponding arguments whenthe method is calledArguments- Appear in the method call - Are the actual values to be used in the method- Are passed to the method’s parameters at the time of thecallII. ExampleSuppose we have two BankAccount objects, one and two, and thetransferFunds method is called:one.transferFunds(5000,two) ;Here again is the definition of transferFunds:public void transferFunds(double amount, BankAccount destination){destination.balance = destination.balance + amount ;this.balance = this.balance - amount ;}In the method, parameter destination is a copy of argument two.III. In Java, All Parameters are Passed By Value- “Pass by value” means that the parameter is a copy of thecorresponding argument- “Copy” means the same value, in a different memory location- Therefore, if a method changes the value (i.e. the contents)of a parameter, it has no effect on the correspondingargument. After all, only the copy was changed See ParamPasser.java, onlineIV. What This Means for Object Parameter Variables(e.g., destination, above)- Remember that the contents of an object variable is not theobject, it is a reference to the object (i.e. the address ofthe object)- So, if a method changes the value (i.e. the contents) of anobject parameter – i.e. makes it point to a different object– the corresponding argument is unaffected (i.e. still pointsto the same object). Again, this is because the new valuewas stored only in the copy- However, any changes made to the object “pointed to” in themethod do affect the corresponding argument. This is becausethe parameter – being a copy of the argument – contains thesame reference (i.e. points to the same object)(This is the purpose of the transferFunds method) See ParamPasser2.java, onlineV. Another Parameter-Passing Mechanism- In some programming languages (not Java!), parameters mayalso be passed by reference- As the name suggests, “pass by reference” means that theparameter is not a copy of the argument, it is an alias forthe object (i.e. another name for the same object)- Of course, in such a situation, any changes made to theparameter are really being made to the argument Sometimes it is said that in Java, primitives are passed byvalue but objects are passed by reference. This is notcorrect. In the case of objects, Java passes a reference– the address of the object - by
View Full Document