Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

is java pass by value or pass by reference?

 
Sunetra Sen
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
A very basic question:
is java pass by value or pass by reference? :-)
Can please someone explain with some example?

Thanks in advance,
Sunetra.
 
Raj Young
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For primitive data type like int, float, double etc., it will be a pass by value.

For objects it will be a pass by reference.

Raj
 
tue march
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi sunetra,

I totally disagree with raj.

Remember everything in java is pass by value.

1. For primitives like int, short, double it is pass by value.

eg: int a=5;
somemethod(a); // here you are passing a copy of a's value to somemethod.

2. Even for object references, it pass by value.
eg: A a = new A(); // object a is created.
somemethod(a); // here you are passing a copy of referece to somemethod.

Raj plz understand java is only pass by value, and there is no point of pass by reference.

Thanks,
Good guy.

[ EJFH: Removed invitation to take discussion off line ]
[ April 19, 2005: Message edited by: Ernest Friedman-Hill ]
 
Ashish Chopra
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Picked the following up from a sun forum that clearly sums up the issue

There are two things that you need to understand :
(i) the actual Java object is never passed - however the reference variable pointing to the object is passed.
(ii) all passing in java is done by value.

What this means for objects is that the reference variable to the object is passed by value. However the passed reference variable still points to the same object.

So when you modify the object pointed to by the passed variable, you are modifying the original object. This means that the object behaves like it was passed by reference, when its reference variable was actually passed by value.

When some authors say the object is passed by reference they are talking about the object behaving as if it was passed by reference. Those who talk about passing by value are talking about the reference variable which points to the object.


Hope this clears things up!!
 
Ravi Srinivas
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
We've got a wonderful Campfire story about this right here..

PassByValue
 
Sunetra Sen
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Guys!
Everything is crystal clear now
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic