Mark Moge wrote:
Can someone explain me why modifyParameters(Integer v1, Integer v2) doesn't change variables even they are passed as references.
Hi Mark,
Actually, what you're doing in that method isn't quite what you're expecting, and it actually doesn't have anything to do with whether or not the objects are passed by reference. What you're actually doing is assigning a new object to the v1 and v2 parameters, so that they're no longer referring to the original objects that were passed in. If you did something like this instead:
That would be closer to what you're expecting, and it would also help explain the difference between pass-by-value and pass-by-reference (at least as I understand it). If Java passed parameters by values, it would create a copy of the object to pass into the method, and you could do whatever you wish to it without having any effect on anything outside of your method:
With passing an object reference to a method, the method has access to the original object itself, and not just a copy of it. In your original code, however, you reassigned the parameters/variables v1 and v2 so that they were no longer pointing at their original objects, but were pointing to the new Integer objects you created.
As a side note, you've probably noticed I've used the "final" keyword on my parameter declarations. The purpose of that is to avoid the exact situation you've come across -- you'll get a compiler error if you try to assign to a parameter that's declared final. That way there's not even a chance that someone comes along and thinks they can modify the object in that way, because 99% of the time it won't be what they're expecting.
I actually had one of my coworkers here -- a really smart guy -- run into this himself the other day and had to explain it there also, so you're not alone ;)