A very basic question:
is java pass by value or pass by reference? :-)
Can please someone explain with some example?
Thanks in advance,
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.
[ EJFH: Removed invitation to take discussion off line ]
[ April 19, 2005: Message edited by: Ernest Friedman-Hill ]
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!!
We've got a wonderful Campfire story about this right here..