File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Garbage collection question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Garbage collection question" Watch "Garbage collection question" New topic

Garbage collection question

Ted Owens

Joined: Jul 25, 2011
Posts: 1
Hi all,

I have a question in regards to Java's object passing in parameters. I know that objects are passed by value.

Say if I have something like this fragment:

//This is created in main()
MyObject x=new MyObject ()

public static void some_function(MyObject o){

My question is that both "x" and "o" refer to the same object. Is the reference to "o"
destroyed when it leaves the function or do I have to explicitly assign o=null; when I'm finished
with it?

Thanks in advance for a reply.
Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3152

The scope of "o" is limited to the method. So once the method completes, the reference variable goes out of scope. Hence it no longer points to the object it was earlier referring/pointing to.

Also please UseCodeTags - that way the code is displayed like a code Welcome to JR!

Mohamed Sanaulla | My Blog
Dmitry Veber

Joined: Jul 25, 2011
Posts: 2
Another thing, You should use your best judgement on when to collect garbage manually or to let Java do it all for you. If you are doing a regular program that does not consume many computer resources, then you don't need to bother your head about it, but if you are making a game or any program that is likely to take tons of comp resources, then I strongly suggest you clear out no longer needed memory allocations as soon as they are no longer needed. (This will improve performance, which is very important for games)
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46412
How do you collect garbage manually? Is it possible at all? Even executing System.gc() isn't guaranteed to do it.
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

technically, you don't pass objects AT ALL. you pass the object reference, and that is passed by value.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
I agree. Here's the link:
subject: Garbage collection question
It's not a secret anymore!