aspose file tools*
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
Author

Garbage collection question

Ted Owens
Greenhorn

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 ()
x.y=30;
some_function(x);
x=null;

public static void some_function(MyObject o){
o.y=10;
}

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: 3071
    
  33

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
Greenhorn

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
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
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
Bartender

Joined: Oct 02, 2003
Posts: 11479
    
  16

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: http://aspose.com/file-tools
 
subject: Garbage collection question