File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question about Local Object Reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question about Local Object Reference" Watch "Question about Local Object Reference" New topic

Question about Local Object Reference

Robbi Palacios
Ranch Hand

Joined: May 25, 2006
Posts: 96

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

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.

Sun Certified Java Programmer 5.0
Sreeraj Harilal
Ranch Hand

Joined: May 09, 2006
Posts: 45
Object and Object references are always create in heap.
Sometimes object reference is create in stack but not object.

SCJP 5.0<br />SCWCD 1.4<br />SCBCD 1.3<br />SCEA part 1
marc weber

Joined: Aug 31, 2004
Posts: 11343

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.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Robbi Palacios
Ranch Hand

Joined: May 25, 2006
Posts: 96
Thanks so much. You guys are el33t!
I agree. Here's the link:
subject: Question about Local Object Reference
It's not a secret anymore!