Friday, June 27, 2008

Java is pass by value.....Always! - Part1


Surprised? Well, lets look at what is pass by value and pass by reference. Let us understand first what is a value and what is a reference. A value of any variable/or java object is the value assigned to it....huh...now what does this means? More technically, a variable is nothing but a name given to a memory location and the value of x is what is stored at the memory location of x. A reference is a pointer to an object. Say its like a remote control through which you can handle the target object. Take help of following figures...

Variable X storing value 7

Reference X storing a remote control

Clearly understand the difference between a value and reference and then you can understand what is pass by value and pass by reference. Well basically as far as java is concerned there is no difference!!Thats why I said java is pass by value always. Let's see why there is no difference. In a pass by value you always pass the underlying value of that variable...that means what ever is stored at the memory place. So if X is a variable and it has value 7 then the memory location contains the number 7. And when you pass by value you actually pass what is stored in the memory..and so 7 is passed! When X is a reference then also same thing happens...whatever is stored at the memory location is passed. But hey wait..in earlier case memory contained 7, but what is here? Here X is a reference, hence it contains a remote control to someone whom it is pointing to..so the memory contains the remote control! So here the remote control is passed! In both cases the value is passed, in first case the value is the actual value and in next case the value is actually the remote control. When you pass the remote control the entity (to which you are passing the remote control) can manipulate the object. In the next post I will demonstrate code for both the cases and then you will be able to point out the exact difference between pass by value and pass by reference. Hey, by pass by reference we mean passing the value..which is infact the remote control(the reference!) :)

1 comment:

Jani said...

A very nice explanation about the topic , Really Liked the substance of your blog . Hoping to visit your blog regularly keep it coming cheers...