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 the Stack and the Heap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question about the Stack and the Heap" Watch "Question about the Stack and the Heap" New topic

Question about the Stack and the Heap

Tim Eapen

Joined: May 28, 2006
Posts: 22
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.


Sandeep Kulkarni

Joined: May 08, 2007
Posts: 6
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

Joined: Feb 28, 2007
Posts: 1710
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.


Louis Moloney
Ranch Hand

Joined: Feb 06, 2007
Posts: 59

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

Joined: Apr 20, 2006
Posts: 3381

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 ]

Everything has got its own deadline including one's EGO!
[CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
I agree. Here's the link:
subject: Question about the Stack and the Heap
It's not a secret anymore!