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 the Stack and the Heap

 
Tim Eapen
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everybody:

I have a question about the following mock exam question on page 263 of Sierra/Bates SCJP book:



Here is the answer:



I don't understand the answer. I thought that ALL objects lived on the heap, along with instance variables.

Thanks,

Tim
 
Sandeep Kulkarni
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Tim,

All objects lived on heap but the question is specifically about object references which can be on stack or on the heap. For eg.

class Test {
String string = null // Object Reference on heap

public void m1() {
String localString = null; // Obj Ref on stack
}
}

I hope this will clear your doubt.
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See the code:



reference variable d1 and p1 will be on the stack. But the person object
encapsulate Dog reference so therefore, the ref variable dog will be on
the heap.


Thanks,
 
Louis Moloney
Ranch Hand
Posts: 59
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tim

what you need to remember is objects ALWAYS live on the heap.

But you can have a reference/pointer on the stack that points to an object on the heap.

In the class below i have 2 String refs (one on heap s1 and one on stack s2 ). The 2 String objects they point to are on the heap.


 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In short, can we say like this?

The Reference variables which are in method-level-scope live in Stack whereas the reference variables which are in instance or class-level-scope live in heap.

All the previous examples seems to conclude this hint.

Am i right?
[ June 03, 2007: Message edited by: Raghavan Muthu ]
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic