Question: Does java support pass-by-value or pass-by-reference?
Answer: Java is pass-by-value for all variables running with in a single virtual machine.
So that means it takes a copy of the variable value and then that copied value will be passed.
So java passes the copy of the bits representing the value. For example, we have declared two int
variables a and b and we have assigned values 10 and 20 to them respectively. We now pass these
variables as parameter to an add() method, which looks like add(a, b). Now what java does is,
it takes a copy of these values and those copied values would be sent to the add method and
not the original values or reference to those values. Whatever happens next in the add method
will not effect the actual values in the variables.
The above explanation is regarding primitive data types. What if we have to pass objects as parameters?
The answer is even the object references are passed by values only. That means java passes a copy of the
bits representing the reference to an object. Here two references point to the same object. So, any change
made by any of the reference will effect the other as well. For example, suppose we have ref1 as a reference
to the object obj. And object obj has a variable a whose value is 15. Now we pass this reference ref1 as a
parameter to a method. So java copies the bits of ref1 and then the copied value is sent. Let us name the
copied reference as ref2. Now suppose ref2 changes the value of variable a in the object to 25. Then the value
of variable a pointed by ref1 will also be 25. Because both ref1 and ref2 are pointing to the same object obj.
No comments:
Post a Comment