hello can anyone tell me how the objects in java are passed by value or by reference. some books say they are passed by reference and some books say they are passed by value. what is true exactly are there any cases where they are passed by value or they are passed by reference. normally i feel objects in java are passed by reference. can anyone hlep me out on this matter. thanks.
Java tenatively passes all parameters to a method 'by value.' That means the current value of the actual parameter is copied into the formal parameter in the method header. Essentially, parameter passing is like an assignment statement, assigning to the formal parameter a copy of the value stored in the actual parameter. This issue ultimately must be considered when making changes to a formal parameter inside a method. The formal parameter is a seperate copy of the value that was passed in, so any changes made to it have no effect on the actual parameter. After control returns to the calling method, the actual parameter will have the same value as it did, prior to the method being called. Calling an object 'by reference' calls the actual object by its memory location. If at some time an object has no references to it, a program cannot use it, and thus the 'garbage-collector' takes heed. The 'garbage-collector' is done periodically or can be called, but what it does is reclaim the memory that was used by the now 'unreferenced' object. Hopefully this can be of some aid to you.. Regards, and good luck, Jonathan W. Zaleski
it gets very confusing... as i think about it, everything is passed by value, but what i really have is a reference to an object. so, the REFERENCE is passed by value. if i have myOjbect objRef = new myObject();, objRef is like an envelope i can use to send mail to the "real" object. i can't touch the real object itself, but i can send and receive messages from it. when i pass objRef into a function, it's like making a NEW envelop with the same address on it. so, i have passed the VALUE of the original envelope into my function. this new envelope will now send mail to the same place, can effect the same changes, etc. to the object down below. note that if i change the address on this new envelope, the address on the old one doesn't change. this is a subtle point. if i use this envelope to change the object, those changes are reflected back in the calling routine when i refer to the object again. but if i change the address on the inner envelope, that does NOT change the address on the outer one - it still points to the same object as before (which may have been changed). i still get confused on this. i know there are some campfire stories from the main page that help explain this. hope i didn't confuse you too much... f
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors