I always thought Java uses pass-by-reference. However, I read a blog post which claims that Java uses pass-by-value. I don’t think I understand the distinction the author is making. What is the explanation?
Home/pass-by-value
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The terms "pass-by-value" and "pass-by-reference" have special, precisely defined meanings in computer science. These meanings differ from the intuition many people have when first hearing the terms. Much of the confusion in this discussion seems to come from this fact. The terms "pass-by-value" andRead more
The terms “pass-by-value” and “pass-by-reference” have special, precisely defined meanings in computer science. These meanings differ from the intuition many people have when first hearing the terms. Much of the confusion in this discussion seems to come from this fact.
The terms “pass-by-value” and “pass-by-reference” are talking about variables. Pass-by-value means that the value of a variable is passed to a function/method. Pass-by-reference means that a reference to that variable is passed to the function. The latter gives the function a way to change the contents of the variable.
By those definitions, Java is always pass-by-value. Unfortunately, when we deal with variables holding objects we are really dealing with object-handles called references which are passed-by-value as well. This terminology and semantics easily confuse many beginners.
It goes like this:
In this example,
aDog.getName()
will still return"Max"
. The valueaDog
withinmain
is not changed in the functionfoo
by creating newDog
with name member variable set to"Fifi"
because the object reference is passed by value. If the object reference was passed by reference, then theaDog.getName()
inmain
would return"Fifi"
after the call tofoo
.Likewise:
In this example,
See lessFifi
is dog’s name after call tofoo(aDog)
because the object’s name was set inside offoo(...)
. Any operations thatfoo
performs ond
are such that, for all practical purposes, they are performed onaDog
, but it is not possible to change the value of the variableaDog
itself.