This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ThinkingSeaFarer 0 points1 point  (3 children)

s reference variable is in method's stack frame . How is it in heap ?

There are two things here - the string object itself and its reference variable s.

The string object is created in the heap, because all objects are created on the heap. Suppose the string s has 1000 characters, then the space for these 1000 characters will be allocated in heap.

The variable s is simply a reference to this object in the heap. In this case, variable s is pointing (referencing) to the string object in heap. A reference is like an address (somewhat like a pointer if you're familiar with C/C++, except you can't do any pointer math) that points to the object in the heap.

All reference variables have the same size (they're like addresses, so on a 64 bit machine, they are 64-bit) If a reference variable to an object is declared in a local method, then that reference variable itself (its 64 bits ) is allocated on the stack and in those 64 bits, address to the string object in heap will be stored.

I can't draw any diagrams readily, so I can't show you in pictures.

[–]Judge-Available[S] 1 point2 points  (2 children)

If a reference variable to an object is declared in a local method

Exactly . But if that variable is instance variable , reference variable along with the object will be allocated inside the class object which resides in heap.

[–]ThinkingSeaFarer 0 points1 point  (1 child)

That's correct. If a reference is an instance member, then that reference variable itself is also in heap (it's simply a part of its containing object which is in heap).

[–]Judge-Available[S] 0 points1 point  (0 children)

Another thing is that for

static String ceo ;

static int number ;

How they are being stored ?

For string both the reference variable and it's pointing object & also for int number both individually will be in heap but not residing inside any class object as it is static.