Does Java
pass by reference or pass by value?
Hi All, Once
upon a time I was in front of an interview panel. Interview panel consist with
two guys and one of them asked “Does Java pass by reference or pass by value”,
from that day onwards it becomes a nightmare for me. Today I am gonna get ride
from it.
I search for
an answer here and there, I’m really tired of searching ….I found some articles
which says “primitives
are passed by value, objects are passed by reference”; this
statement is partially incorrect. There is no doubt in “primitives are pass by value”. Problem arise when we start to think
about object passing.
Before going
in-depth of this discussion, let’s separately discuss the meanings of pass-by-value and pass-by-reference meanings. Below I mention the best description I
found on it from Scott Stanchfield’s
article.
Pass-by-value
The actual parameter (or argument
expression) is fully evaluated and the resulting value is copied into
a location being used to hold the formal parameter's value during
method/function execution. That location is typically a chunk of memory on the
runtime stack for the application (which is how Java handles it), but other
languages could choose parameter storage differently.
Pass-by-reference
The formal parameter merely acts as
an alias for the actual parameter. Anytime the method/function
uses the formal parameter (for reading or writing), it is actually using the
actual parameter.
Now the time
to clear our mess “Objects are passed by reference”
A correct way of expressing
that in java is “Object references
are passed by value”
Here I’d like to share simple and popular example to have better
understanding about the above context
Let’s add
something more.
When you
pass aDog to the foo()
method, Java passes the references by value just like any other parameter. This
means the references passed to the method are actually copies of
the original references. Below figure shows two references pointing to the same
object after Java passes an object to a method.
Java copies
and passes there reference by value, not the object. Thus, method
manipulation will alter the objects, since the references point to the original
objects.
Our final conclusion is everything in java is “primitives are passed by value, objects
I’d
like to share the references that I have used while writing this document
No comments:
Post a Comment