aspose file tools*
The moose likes Beginning Java and the fly likes Heap and Stack Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Heap and Stack" Watch "Heap and Stack" New topic
Author

Heap and Stack

podonga poron
Ranch Hand

Joined: May 12, 2008
Posts: 55
class example{

String s = "one"; // goes to the Stack ?
// if this is true WHY ? aren't strings treated like objects (auto-wrap)?

String s2 = new String("two"); // goes to the Heap ?

int i = 3; // to the Heap ?

example e = new example(); // Stack ?

}


Stack is in the Ram Memory ?

Heap is in the HD ?

i read that both (stack and heap) lives in the Ram, but that doesn't make sense because you have to worry about the Stack and you can use freely the Heap ...

please help me here, as you can see i'm really confused ..
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39393
    
  28
Not sure, but I thought all fields which are objects (the three Strings, and the one "example") are referred to as references on the heap. Not sure, but I think the int is a value on the heap.

The heap and stack both usually, as far as I know, live in RAM, but if there is overloading of RAM there may be paging to the hard drive. That is an OS problem, which you don't have to worry about, though buying a bit of extra RAM may be useful.

Your example given has however got an infinite recursion in, which will fill up both your heap and your stack, only it is likely that you will run out of stack space before you run out of heap space!
podonga poron
Ranch Hand

Joined: May 12, 2008
Posts: 55
lol is true, but i wrote that example looking for answers, and i didn't think about compiling
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2902
    
    1

references are stored on stack, where Objects are stored on heap .

Heap is not necessarily on HDD, its paging concept comes in to a picture when RAM memory is running low .


[LEARNING bLOG] | [Freelance Web Designer] | [and "Rohan" is part of my surname]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39393
    
  28
Originally posted by Sagar Rohankar:
references are stored on stack, where Objects are stored on heap.
Yes, that is rather clearer than what I said. Thank you.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Originally posted by Campbell Ritchie:
Yes, that is rather clearer than what I said. Thank you.


Clearer, but still not really correct -- an object can contain references as member variables, and those references, being a part of the object, are on the heap.

Here's a better version:

"Local variables are stored on the stack; everything else is on the heap."


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Heap and Stack