Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Pass-by-reference or Pass-by-value

807607Nov 29 2006 — edited Nov 30 2006
Hi,

When objects are passed to methods through parameters, would it be pass-by-reference or pass-by-value?

Comments

807607
No pass-by-reference in Java.

All parameters are always passed by value.
807607
java always passes it by value
807607
Not to mention objects are never passed. References are passed and they're passed by value.
796440
Java is always pass-by-value. Always.

Always. Always. Always.

http://javadude.com/articles/passbyvalue.htm
http://java.sun.com/developer/JDCTechTips/2001/tt1009.html#tip1
http://www.javaranch.com/campfire/StoryPassBy.jsp
http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
http://www-106.ibm.com/developerworks/library/j-praxis/pr1.html
http://www.cs.toronto.edu/~dianeh/tutorials/params/
http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#38698
http://radio.javaranch.com/channel/val/2004/05/21/1085125887000.html
807607
OK. guys. Let me do a simple example here.

class A
{
int a,int b;
}
class B
{
public static void main(String args[])
{
A ob = new A();
ob.a = 10;
ob.b = 20;
System.out.println("Before swapping "+ob.a+" "+ob.b);
swap(ob);
System.out.println("After swapping "+ob.a+" "+ob.b);
}
public static void swap(A obj)
{
int temp = obj.a;
obj.a = obj.b;
obj.b = temp;
}
}

After calling swap(), a and b values are getting changed. So it is pass by reference right? If it is pass by value, it will affect i.e local copy in method only will affect. Am I right?
807607
for array and objects, i will create a refernce ,
807607
Java is always pass-by-value. Always.

Always. Always. Always.

http://javadude.com/articles/passbyvalue.htm
http://java.sun.com/developer/JDCTechTips/2001/tt1009.
html#tip1
http://www.javaranch.com/campfire/StoryPassBy.jsp
http://www.javaworld.com/javaworld/javaqa/2000-05/03-q
a-0526-pass.html
http://www-106.ibm.com/developerworks/library/j-praxis
/pr1.html
http://www.cs.toronto.edu/~dianeh/tutorials/params/
http://java.sun.com/docs/books/jls/second_edition/html
/classes.doc.html#38698
http://radio.javaranch.com/channel/val/2004/05/21/1085
125887000.html
hehe :-)
807607
No, you are wrong. There is no such thing as pass by reference in Java. Once again you do not seem to understand that the object is not passed. The variable "obj" is not an object, it is a reference. The value is copied, this is pass by value. Because it is copied both variables point to the same instance of class A. You are then modifying that object's instance variables, you're not actually changing the variable passed.
807607
class A
{
      int a,int b;
}
class B
{
       public static void main(String args[])
       {
                A ob = new A();
                ob.a = 10;
                ob.b = 20;
                System.out.println("Before swapping "+ob.a+" "+ob.b);
                swap(ob);
                System.out.println("After swapping "+ob.a+" "+ob.b);
       }
       public static void swap(A obj)
       {
                int temp = obj.a;
                obj.a = obj.b;
                obj.b = temp;
       }
}
796440
After calling swap(), a and b values are getting
changed. So it is pass by reference right?
No.

The refernce is being passed by value (which is not the same as the object being passed by reference).

If Java did pass by reference, then you could do
tmp = a;
a = b;
b = tmp;
and the caller would see the results. When you dereference the parameter with a.whatever = ..., the fact that the caller sees the change does not indicate pass by reference.
796440
for array and objects, i will create a refernce ,
And?

Java is still purely PBV.
807607
java support only pass by value,

when u pass obj to a method , the function will create referece to actual Object,
807607
java support only pass by value,

when u pass obj to a method , the function will
create referece to actual Object,
Nonsense. The object is never passed. The reference is passed by value.
class A {

    int a;
    int b;

    public static void main(String[] args) {
        // obj is a reference that "points" to an instance of A
        A obj = new A();
        // The reference is passed, but it is passed by value because
        // the value of "obj" is copied.
        swap(obj);
        System.out.println(obj.a);
        System.out.println(obj.b);
    }

    static void swap(A arg) {
        // The variable "arg" is a reference that points to an instance of A
        // It's value has been copied from "obj" when it was passed in the
        // main method.  Modifying "arg" will not modify "obj".

        // This is not modifying "arg", it is dereferencing "arg" and modifying
        // the value of the variables "a" and "b" of the instance of A that "arg"
        // points to which would be the same as the instance "obj" points to.
        arg.a = 10;
        arg.b = 20;

        // This modifies the value of "arg" to point at a new instance of A
        // This would not affect "obj", they would now point at two different
        // objects
        arg = new A(); // Does not affect "obj"
        // This has no effect on "obj" because we're changing the values of
        // a and b on a different instance of A
        arg.a = 30;
        arg.b = 40;
    }

}
807607
i got doubt, if java support pass by value, then the out put of previous exp should be same as before method call. but values r changed?

any one explanin it clearly?
796440
i got doubt, if java support pass by value, then the
out put of previous exp should be same as before
No. Read the links. Read my previous explanation.

Inside the method, a = somethingElse is very different than a.someField = somethignElse.

If a = somethingElse changes the caller's variable, then it's pass by reference. But for a.someField, you just have two different reference variables pointing to the same object, and we changed that object's contents.

The referene is passed by value. A copy of the paramter (the reference) is made, and the method uses that copyh. When the method changes the value of that copy, with a = somethingElse, the caller is not affected. This is the definition of PBV.

When you change what the variable points to and it's seen by the caller, that has nothing to do with PBR.
807607
In Java-The complete reference book, in the page no 133 in 5th Edition, it is mentioned that, Objects are passed to methods by use of call-by-reference. Changes to the objects inside the method do affect the object used as an argument.

It is given with example.

Please go through with google book search and turn it to page 133 and let me know.
807607
ya i agree with u vimsy_vinay

i have seen this in Java Certification Book also
796440
In Java-The complete reference book, in the page no
133 in 5th Edition, it is mentioned that, Objects are
passed to methods by use of call-by-reference.
The book is wrong.

Read the links I provided. By the definition of call by reference, a change to the value of the parameter inside the method has to be reflected in the caller. The object is not the parameter, the reference variable is. Changing the reference variable inside the method does not affect the caller. Therefore, NOT PBR.
796440
Java is always pass-by-value. Always.

Always. Always. Always.

There is exactly one parameter passing mode in Java -- pass by value -- and that helps keep things simple.
-- James Gosling, "The Java Programming Language, Second Edition"
(James Gosling being the father of Java)


Java is always pass-by-value. Period. Repeat after me: Pass-by-value.

Now, Java does use the term "reference" to describe variables that are used for accessing objects, as opposed to primitives. And when you "pass an object" to a method, you're really passing a copy of a reference to that object. But passing a copy of a reference is passing that reference by value.

Despite the apparent intuitively obvious association, passing a reference by value is not--I repeat: NOT--the same as passing by reference. Don't even go there. It's not.

Java is 100% pure, unadulterated pass-by-value. Passing a reference by value is not the same as pass-by-reference.

No, you can't "just call it pass-by-reference to keep it simple." Pass-by-reference has a very specific meaning in computer science, and that is not consistent with how Java passes references by value. Using the term incorrectly will not "keep it simple." It will muddy the issue.
class Foo {
    String str_;
}

...

void m1(String str) {
    str = "abc";
}

void m2(Foo foo) {
    foo.str_ = "xyz";
}

String s = "ORIGINAL";
Foo f = new Foo();
foo.str_ = "ORIGINAL";

m1(s);
m2(f);


System.out.println(s); // prints "ORIGINAL"
System.out.println(f.str_); // prints "xyz"
For further explanations of what pass-by-value is and why Java is pass-by-value, see the following:

http://javadude.com/articles/passbyvalue.htm
http://java.sun.com/developer/JDCTechTips/2001/tt1009.html#tip1
http://www.javaranch.com/campfire/StoryPassBy.jsp
http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
http://www-106.ibm.com/developerworks/library/j-praxis/pr1.html
http://www.cs.toronto.edu/~dianeh/tutorials/params/
http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#38698
807607
In Java-The complete reference book, in the page no
133 in 5th Edition, it is mentioned that, Objects are
passed to methods by use of call-by-reference.
Changes to the objects inside the method do affect
the object used as an argument.

It is given with example.

Please go through with google book search and turn it
to page 133 and let me know.
Either you're misquoting or that book is inaccurate and in a horrible way too.

References are passed by value.
Primitives are passed by value.

Objects are never passed.

That's all there is to it. Confusion often results from the use of the word "reference" to describe what is essentially a pointer and from ignorant programmers not understanding that the variable is not an object, it is a reference.
807607
The same James Gosling and Herbert Shildt put the example in 133th page in fifth edition mentioning in the example
// Objects are passed by reference

Class Test{
    int a,b;

......
So whom do I blame?
796440
The same James Gosling and Herbert Shildt put the
example in 133th page in fifth edition mentioning in
the example
// Objects are passed by reference> ....
I rather doubt Gosling said that.

Objects are not passed by reference. References are passed by value. The two are different. If you read enough of the JLS, and if you understand what PBV and PBR mean, you'll see that there's absolutely no question.
807607
The same James Gosling and Herbert Shildt put the
example in 133th page in fifth edition mentioning
in
the example
// Objects are passed by reference>
....
I rather doubt Gosling said that.

Objects are not passed by reference. References are
passed by value. The two are different. If you read
enough of the JLS, and if you understand what PBV and
PBR mean, you'll see that there's absolutely no
question.
I know what is pass-by-ref and pass-by-value.

In C,
main()
{
           int a=10,b=20;
           swap(a,b);
           printf("%d %d",a,b);
}
swap(int a,int b)
{
      int t=a;
      a=b;
      b=t;
}
Above is pass-by-value;
main()
{
           int a=10,b=20;
           swap(&a,&b);
           printf("%d %d",a,b);
}
swap(int *a,int *b)
{
      int t=*a;
      *a=*b;
      *b=t;
}
Above is pass-by-reference. The same effect is happening when we pass objects in Java.

Why don't we call it as PBR?
791266
Why don't we call it as PBR?
Why not read the links? We don't have PBR. We can't implement a swap method that swaps two ints.

Kaj
791266
In Java-The complete reference book, in the page no
133 in 5th Edition, it is mentioned that, Objects are
passed to methods by use of call-by-reference.
Changes to the objects inside the method do affect
the object used as an argument.

It is given with example.

Please go through with google book search and turn it
to page 133 and let me know.
Page 133 is not part of the preview. Post exactly what the books says.
807607
ya i agree with u vimsy_vinay
even though there are several experts right here telling you that java is always pass-by-value? fair enough

the book is either wrong, or it has been misinterpreted
807607
The same James Gosling and Herbert Shildt put
the
example in 133th page in fifth edition
mentioning
in
the example
// Objects are passed by reference>
....
I rather doubt Gosling said that.

Objects are not passed by reference. References
are
passed by value. The two are different. If you
read
enough of the JLS, and if you understand what PBV
and
PBR mean, you'll see that there's absolutely no
question.
I know what is pass-by-ref and pass-by-value.

In C,
main()
{
int a=10,b=20;
swap(a,b);
printf("%d %d",a,b);
a,int b)

int t=a;
a=b;
b=t;
e]
Above is pass-by-value;
main()
{
int a=10,b=20;
swap(&a,&b);
printf("%d %d",a,b);
a,int b)

int t=*a;
a=b;
*b=t;
e]

Above is pass-by-reference. The same effect is
happening when we pass objects in Java.

Why don't we call it as PBR?
because it isn't PBR. you can keep asking as much as you like, and you're not obliged to believe a word anyone tells you, but no matter what happens, java will always be pass-by-value

why do people think that if they repeat the same wrong thing enough times, it will become the right thing??
807607
GOD DO WE HAVE TO GO THROUGH THIS AGAIN?
796440
I know what is pass-by-ref and pass-by-value.
No, you don't.


main()
{
int a=10,b=20;
swap(&a,&b);
printf("%d %d",a,b);
*a,int *b)

int t=*a;
*a=*b;
*b=t;
e]

Above is pass-by-reference. 
No. That's passing pointers by value.

C, like Java, is always 100% pure PBV.


The same effect is
happening when we pass objects in Java.
We don't pass objects in Java. We pass references by value.



Why don't we call it as PBR?
Because it's PBV. The definition of PBV is when the parameter's value is copied and that copy is what the method or function gets. This is what always happens in C and in Java.

C++ supports PBR, but C and Java do not.
807607
In Java-The complete reference book, in the page
no
133 in 5th Edition, it is mentioned that, Objects
are
passed to methods by use of
call-by-reference.
Changes to the objects inside the method do affect
the object used as an argument.

It is given with example.

Please go through with google book search and turn
it
to page 133 and let me know.
Page 133 is not part of the preview. Post exactly
what the books says.
http://books.google.co.in/books?vid=ISBN0072230738&id=saj_wnV2xXoC&pg=PA133&lpg=PA133&ots=q-29ha9LqG&dq=call-by-reference+in+java&sig=dZ_fDK91cwL3INIhLisdhycgvVE
807607
because it isn't PBR. you can keep asking as much as
you like, and you're not obliged to believe a word
anyone tells you, but no matter what happens, java
will always be pass-by-value

why do people think that if they repeat the same
wrong thing enough times, it will become the right
thing??
I agree after confirming this is the mistake of the book that is written by James Goslisg( Father of Java) and Herbert Shildt.
C++ supports PBR, but C and Java do not.
swap(&a,&b);
Calling swap() by specifying memory address of the variable nothing but reference. This is same in C and C++.
800322
http://books.google.co.in/books?vid=ISBN0072230738&id=
saj_wnV2xXoC&pg=PA133&lpg=PA133&ots=q-29ha9LqG&dq=call
-by-reference+in+java&sig=dZ_fDK91cwL3INIhLisdhycgvVE
The paragraph in the book is horribly wrong. Gosling himself said "Java is always pass-by-value, this keeps things simple".
798906
Oh God ... the book is wrong since the reference does not get passed, what gets passed is a copy of the reference (this is pass by value)
791266
The same James Gosling and Herbert Shildt put the
example in 133th page in fifth edition mentioning in
the example
I can't find anything which indicates that Gosling was a co writer of that book.

The book doesn't say that it is pass by value. It says that it's effectivly like pass by reference since the method can modify the object. The method can still not modify the reference so it is pass by value.

Kaj
796440
C++ supports PBR, but C and Java do not.
swap(&a,&b);
Calling swap() by specifying memory address of the
variable nothing but reference. This is same in C and
C++.
Incorrect. In C, there is only PBV. In C++, whether a method is PBV or PBR depends on its signature. Just because you happen to pass an address, that does NOT make it PBR.

In both C and C++, this is a function that accepts int pointers passed by value:
void primPtrByVal(int* param1, int* param2) {
    int* tmp = param1;
    param1 = param2;
    param2 = tmp;
}
You can call it like so:
int i = 1;
int j = 2;
primPtrByVal(&i, &j);
Note that we are NOT passing i and j by reference. We are passing their addresses by value.

In PBV, the parameter's value is copied, by definition. That's what always happens in both C and Java.

Note that doing param1= inside the function does not affect the caller. Therefore, by definition, it is not pass by reference.


Here's a PBR function in C++. It takes ints passed by reference. You cannot do PBR in C or Java.
void primByRef(int& param1, int& param2) {
    int tmp = param1;
    param1 = param2;
    param2 = tmp;
}
You call it like so:
int i = 1;
int j = 2;
primByRef(i, j);
Note that, unlike the previous PBV function, here when we do param1=, the caller's variable is affected. In PBR, the function gets an "alias" of the caller's variable.
800322
The book doesn't say that it is pass by value. It
says that it's effectivly like pass by reference
since the method can modify the object. The method
can still not modify the reference so it is pass by
value.
Well, the comment says pass by reference, and this is plain wrong. And IMO it's more than foolish to use that "effectively like" description to explain that mechanism. Since there is no way to actually do any of the stuff PBR would allow you to (swapping references), it is not *effectively like PBR" anyway. It is very effectively PBR though and behaves exactly like it. :)
796440
plain wrong. And IMO it's more than foolish to use
that "effectively like" description to explain that
mechanism.
Right. Saying that "passing a reference by value is 'like' passing an object by reference" is equivalent to saying "the earth rotating on its axis is 'like' the sun revolving around the earth."

In both cases, if you severely limit your view, the real thing can appear similar to the "like". But then when you go beyond that very narrow view, you have to start inventing other overly complex explanations for things that are mutually incompatible.
800322
But then when you go beyond that very narrow view, you have to
start inventing other overly complex explanations for
things that are mutually incompatible.
Which is actually done, much to our amusement. :)
800282
The same James Gosling and Herbert Shildt put the
example in 133th page in fifth edition mentioning in
the example

// Objects are passed by reference

Class Test{
int a,b;
....

So whom do I blame?
Checkout reply 36 from this deleted thread:
http://209.85.135.104/search?q=cache:r9QUhpsh5uEJ:forum.java.sun.com/thread.jspa%3FthreadID%3D787340%26start%3D30+jos+herbert+java&hl=en&ct=clnk&cd=1

At first I thought Jos was exaggerating, but it is true!
807607
I know what is pass-by-ref and pass-by-value.
...
In C,
C is a pure PBV language.
main()
{
int a=10,b=20;
swap(&a,&b);
printf("%d %d",a,b);
*a,int *b)

int t=*a;
*a=*b;
*b=t;
e]

Above is pass-by-reference.
No it isn't.

The same effect is
happening when we pass objects in Java.
Indeed.
Why don't we call it as PBR?
Because it's PBV.
807607
Never ceases to amaze me the prolific amount of stupidity. Several experts on these forums tell you it's PBV. Gosling says it's PBV. Countless articles by other experts, including the language's designers say it's PBV. Yet because of one inaccurate comment in a book you think we're all wrong?

We've also explained numerous times why it's PBV and not PBR and why your conclusions are horribly flawed and based upon inaccurate, naive and ignorant understandings of what a reference in Java is and what is actually being passed.
807607
Here is what James Gosling (et al.) actually says:

The Java programming language does not pass objects by reference; it passes object references by value. Because two copies of the same reference refer to the same actual object, changes made through one reference variable are visible through the other. There is exactly one parameter passing mode -- pass by value -- and that helps keep things simple.

-- Arnold, K., Gosling J., Holmes D. (2006). The Java� Programming Language Fourth Edition. Boston: Addison-Wesley.
807607
if i say you are right....java has PBR, are you going to give me the duke $$$...??
>
I know what is pass-by-ref and pass-by-value.
No you don't.
In C,

swap(int a,int b)

Above is pass-by-value;
Correct.
swap(int a,int b)

Above is pass-by-reference.
Wrong.

C is a language. It doesn't matter how you write the C code it is always pass by value. By definition it can not pass by reference.

The method is passing a value and only a value. The fact that the value is a pointer has nothing to do with it.

From "The C Programming Language" by K&R, Section 1.8....

-----------------------------------------------

In C, all function arguments are passed "by value".

-----------------------------------------------
>
C++ supports PBR, but C and Java do not.
swap(&a,&b);

Calling swap() by specifying memory address of the
variable nothing but reference. This is same in C and
C++.
Several things wrong.

First it doesn't matter how you call the method. It matters how the parameters are passed to the method.

Thus the above could be pass by reference in C++, but NOT because of the way you posted the call.

Second you think that the fact that you are taking the address has defines the passing mechanism. You are wrong - it does not.

Third presumably you are using the following definition for swap...

void swap(int* a, int* b);

The above definition works for both C and C++. And in both cases the passing mechanism is by value. That is not how one defines pass by reference in C++.
807607
OK. Thanks guys. Better closing this thread. Dukes shared for all the responsers. Have a nice day.
OK. Thanks guys. Better closing this thread. Dukes
shared for all the responsers. Have a nice day.
And does that mean you now understand how passing mechanisms relate to java and C?
807607
if i say you are right....java has PBR, are you going
to give me the duke $$$...??
You'll certainly get nukes.
807607
OK. Thanks guys. Better closing this thread. Dukes
shared for all the responsers. Have a nice day.
And does that mean you now understand how passing
mechanisms relate to java and C?
It probably means he's constipated by the discovery.
1 - 49
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Dec 28 2006
Added on Nov 29 2006
49 comments
2,540 views