• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage collection question

 
Ted Owens
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3159
33
Google App Engine Java Ruby
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Dmitry Veber
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 12101
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
technically, you don't pass objects AT ALL. you pass the object reference, and that is passed by value.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic