File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about Local Object Reference

 
Robbi Palacios
Ranch Hand
Posts: 96
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

If I had a method that returns an Object that I
declared locally inside the same method, what will
happen?


public class Foo() {

public Rabbit getRabbit() {
return new Rabbit();
}
}

1. What if I use the method to instantiate a newly created
Object of the same type. ( ie. Rabbit r = x.getRabbit() );

Will the object returned from x.getRabbit() still exist after
the method stops executing?

2. I need some clarification. I read that all objects instantiated
are created on the heap regardless whether they are created in
methods. Is that true?

3. Also, all methods are created in the stack. But what happens when
an object is initialized? Does methods get initialized too?


Thanks in advance.
 
Sreeraj Harilal
Ranch Hand
Posts: 45
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Object and Object references are always create in heap.
Sometimes object reference is create in stack but not object.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're not really declaring a local variable in this method. You're simply creating a new object (on the heap, where all Java objects live) inside the method, then returning a reference to that object.

But suppose that you did declare a local variable that pointed to that object...

In this case, the variable "fred" would be destroyed when the method exits, but the object that fred pointed to would still exist on the heap. At this point, whether that object is eligible for garbage collection depends on whether there are any other references to it. And since getRabbit returns a Rabbit, it's likely that when you call the method, you will assign the Rabbit reference to a variable outside of the method. For example...

Rabbit albert = getRabbit();

Here, a new Rabbit would be created (on the heap) and the local variable fred would reference it. The fred variable would be destroyed when the method exits, but the variable "albert" would still be pointing to the object.
 
Robbi Palacios
Ranch Hand
Posts: 96
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks so much. You guys are el33t!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic