This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Anything with NEW keyword => heap
Anything else locally declared =>stack
Joined: Oct 16, 2008
Duran now tell me about this code, what will be store where, this is your test:
Joined: Aug 17, 2007
String s = "abc";
"abc" will go in the pool and s will refer to it.
String s = new String("abc");
Java will create a new String object
in normal (non-pool) memory, and s will refer to it. In addition, the literal "abc" will
be placed in the pool.
Punit From this I doubt that Pooll contains only references as per that tutorial :-(
Joined: Oct 16, 2008
A string literal is always of type String (§4.3.3. A string literal always refers to the same instance (§4.3.1) of class String. JLS String Literal
This means String Literals are just references to the instances of class String. It clears that String literal pool contains literals means only references to String instance. So if String s="abc"; is called "abc" will be created as String Instance on the heap and its literal means its reference will be stored in the pool.
All objects are created in Heap. If you are creating any Objects in method like
Then its reference will be present in stack and Object will be in heap. Once the Method finishes its execution the whole stack frame is blown up and thus now there are no more references to the locally created Objects. So all the Objects which were created becomes eligible for GC. In case you return the reference of any Object then you can even access it after the completion of the method.
About the primitive types they live in the stack frame. So as all know there life time is only till the execution of the method.
Punit Singh wrote:If you do not use new keyword, variables will not be created in the heap.
Watch out that you use the language exactly right: variables are not created on the heap, you meant objects instead of variables here. A variable of a non-primitive type is a reference to an object in Java.