• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Question about the Stack and the Heap

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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,
 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.


 
Ranch Hand
Posts: 3389
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic