Monday, April 21, 2008

Does Java pass by reference or pass by value?

A compact answer to this question will be

"Java passes the reference of the object by value".
So what does it mean to pass the reference of the object by value.
It means that if an object is passed to a method, then the object itself can be altered but not its reference. Because the reference of the object is passed by value. For example consider a object O and let the reference of the object O be x. Now when you pass the object O to a method, the VM internally makes a copy of x, that means there is another reference y which points to the same location as x does.
But x >< y. Now this means whenever you pass a object to a method, the object has atleast two references. Thus objects in java can be altered by passing to a method but they cannot be swapped with another object or assigned to some other object or something like that.

No comments: