Harman Kadron Interview Question
Java DevelopersCountry: United States
Interview Type: Phone Interview
But if an object contains a primitive type, that primitive type will be on the heap. So not all primitives are stored on the stack. I'm not sure whether that is or is not what you meant in your answer.
Primitive data types are stored in stack unless they are part of an object.Objects/instances are stored on heap and if Objects/Instances contains primitive data types then in this case primitive data types are stored on heap.
When a method is called , a frame is created on the top of stack.
Once a method has completed execution , flow of control returns to the calling method and its corresponding stack frame is flushed.
Local variables are created in the stack
Instance variables are created in the heap & are part of the object they belong to.
Reference variables are created in the stack.
The storage of primitive data types depends upon the type of the variable.
If the variable is a local variable whose scope is with in the method then it is stored in "stack".
If the variable is a static variable whose scope the entire class then it is stored in the "Class context area",where as if the variable is a non static variable whose scope is with in the object then it is stored in the "Heap"
It does not depend on whether it is a primitive data type or not, It depends on whether it is an Instance variable or a local variable.
All local variables are stored in the stack along with their methods within which they are declared.
All instance variables/objects which contain primitive types are stored on the heap even if they are declared inside a method.Only their references stay in the stack if declared inside a method.
Stack memory stores primitive types and the addresses of objects.
- Expressions April 03, 2013The object values are stored in heap memory. An object reference on the stack is only an address that refers to the place in heap memory where that object is kept.