I have not been able to find any reliable literature on this but i'm curious as to where an object is stored if its created inside of a method ? on the stack or on the heap in java 8?
public class A {}
.
.
.
public class B {
public void test(){
A m = new A();
}
}
I know that normally only local primitives, reference variables and function calls are stored on the stack and that objects are stored in the heap
So I'm assuming that one of the following two scenarios is true either
Case 1 : Objects instantiated in a method are as usual stored in the heap with a reference to that object in the stack then when the function finishes the object reference goes out of scope and the object in the heap is then available for garbage collection
Case 2 : Objects instantiated in a method are stored in the stack then are available for garbage collection when function finishes
I strongly suspect its case 1, it wouldn't make sense to store an object in a stack, the only reason I have doubts is because ive come across some literature saying on the stack and others on the heap
Thanks for your feedback ahead of time
The local reference variable is on the stack, and the object is in the heap.
Note that your question title,
Instance declared inside of a Method
is misleading since objects/instances are declared nowhere -- only variables are, and the object created in a method can be placed on fields into a collection, or anywhere it's needed. And so there is no guarantee that the object should be GC'd when the method exits.
All the objects are stored in the heap ... the garbage collector runs whenever there's a lack of memory so it get rid of the objects that are not used anymore and there's no reference to them too.
Your assumption specified in Case 1 is correct. Here is a good source on memory allocation in java.
Java Heap Space vs Stack – Memory Allocation in Java
If they are not immediate "values" (not like an int property in a class object), only their reference values are stored in the stack. their actual values and structures are stored in the heap.
these are stored in the stack as they are;
int i=10;
float f=10.00;
bool b=true;
these will have only references on the stack, they will reside in the heap (any kind of class variable is part of the structure and be created on the heap altogether);
int[] ii={1,2,3};
double[] dd = new double[10];
String s="String!!";
Object o=new Object();
when passed to a method, Values are copied to a new stack variable (unless converted to a reference object). References are also passed to a copycat stack variable, but since they are references, both will redirect to the same object (unless copied to a whole new object manually).
this part might not be of interest in the topic, you decide
In the following code, number is created on the stack and copied to a new stack value for the method, hello created on the heap, passed by reference to s then two strings concatenated on another heap address and it now holds this new address (strings are immutable). The Point object is not immutable as strings, so it can be changed anywhere you referenced it as they are created on the heap to access freely.
class Point{ int x;int y; Point(int x,int y){this.x=x;this.y=y;} }
public class TestClass{
public static void main(String []args){
int number=5;
String hello="Hello";
Point point = new Point(2,4);
Print(number,hello,point);
System.out.println(hello+" "+number+" "+point.x+" "+point.y);
}
public static void Print(int i,String s,Point p){
i+=5;
s+="World!";
p.x+=2; p.y+=2;
System.out.println(s+" "+i+" "+p.x+" "+p.y);
}
}
Related
This question already has answers here:
Where does class, object, reference variable get stored in Java. In heap or in stack? Where is heap or stack located?
(8 answers)
Closed 4 years ago.
This question is regarding Java, and how Objects are created, passed, and "deleted".
From what I know, when you want to create an object, you use the "new" keyword. From my understanding, this operator (new) allocates memory for the object, and the = operator assigns the reference to the location of this object in memory, to the variable name you give it.
For example, let's say you create an array in Java like so.
int[] arrayX = new int[size];
the = operator now stores the reference to the array in memory to the variable name arrayX.
This is all fine.
Now let's think about methods (functions).
Firstly, from my understanding, when you call a method, memory is allocated on the stack for this method's variables and processes, and when the method returns, it's instance on the stack is closed/deleted/put in garbage. However, this doesn't explain how you can return objects (such as arrays) which were created in the method back to the caller's scope using the return keyword.
From what I understand, since the method is returning, the data in its stack is going to be deleted. Therefore, the array that was created within this method's scope, will also be deleted. So the reference returned to the array's location, will point to "garbage" values. However, this is clearly not the case. In Java, if you return an Object, you can keep using it.
This makes me confused about how Objects are created, stored and returned...
are objects created always stored in permanent memory? or
does the return operator move the array or object from the method's temporary stack to the caller's stack?
if the second case is true, then are objects created within methods deleted after the method returns to the caller (but does not return the object)? In this third case, it would mean that one shouldn't worry about creating objects in methods, as those objects will be deleted. Thus, if a program was to call a method 1000 times, we shouldn't worry about the memory filling up with objects that we only use once.
I have looked through courses offered on edX on Java and even read a book (although not finished) and still haven't found an answer to this so I would appreciate your input (if you know).
EDIT: Please note, this questions asks 3 separate things:
1. Where are Objects and primitives stored
2. what does the new operator do specifically
3. what does the return operator do
However, this doesn't explain how you can return objects (such as arrays) which were created in the method back to the caller's scope using the return keyword
The reason you can do it is that the object is not created on the stack; only the reference to it is. The array stays in the dynamically allocated memory until it becomes eligible for garbage collection. When you assign the result returned from a method to another variable or to a field, the value of the reference is preserved, so the object stays in memory.
does the return operator move the array or object from the method's temporary stack to the caller's stack?
Only the value of the reference gets copied. The reference is a relatively small object, whose size depends only on the system on which JVM is running. In particular, the size of the reference does not change with the size of the object being referenced, so the amount of required copying is limited.
One important point to note is that if you return an object in a method and don't save it, it does in fact get garbage collected. For example if you have:
public int somemethod(){
int myint = 9;
return myint;
}
And then call someMethod() in your main method, in order to access this return for the future you have to store it.
public static void main(String [] args){
this.someMethod(); //can't access myInt.
int savedInt = someMethod(); // Saves the value 9 for future access.
}
So in general when you call a method and then the return type is present before that method gets removed from the stack, but in order to use it in the future you must store the value in a variable that will still be present.
suppose i have a code snippet like this:-
class A {
void help() {
Help helper = new Help();
}
}
in the above case, the object reference helper will be allocated memory in the stack.
now if i have a case like this
class A {
Help helper = new Help();
}
in this case, helper will not be allocated memory inside of a stack frame(I am sure of that).
will it behave like an instance variable and will be allocated space inside of an object on heap.
This type of declaration is only located to your instance. the helper attribute will be assigned each time you instanciate you Class A.
It is definitely an instance variable. it goes in the heap
In order to separate the instance and the variable you can use static attribute. Then it is linked to the class so it goes in the code segment.
Yes, You are correct. In the second case, the Help object will behave as an instance variable of the class.
When you declare the object inside the function, stack memory is used up (local variables). Whereas for instance variables ,heap memory is used.
Yes, in the second case the memory will be allocated to object helper as soon as the object of class A will be initialized but in the first case the memory will be allocated on the stack to the function named void help() and will be destroyed as soon as the function ends because helper object is a local variable to this function.
There is a difference between object and reference variable. For example:
//Here 'helper' is the reference variable
Helper helper = new Helper ();
Whenever we create any object (new Helper()), it’s always created in the Heap space and it's reference (helper) in the Stack space.
Java Stack memory is used for execution of a thread. They contain
method specific values that are short-lived and references to other
objects in the heap that are getting referred from the method.
(Source: https://www.journaldev.com/4098/java-heap-space-vs-stack-memory#java-stack-memory)
So the two objects are stored in the heap but their two reference variables are stored in different stacks.
I don't have much idea on Java.
I was going through few links and found blog says "Java Primitives stored on stack", which I feel it depends on instance variable or local variable.
After going through several links my conclusion is,
Class variables – primitives – are stored on heap as a part of Object which it contains.
Class variables – object(User Defined) – are stored on heap as a part of Object which it contains. This is true for both reference and actual object.
Method Variables – Primitives – are stored on stack as a part of that stack frame.
Method Variables – object(User Defined) – are stored on heap but a reference to that area on heap is stored on stack as a part of that stack frame.
References can also be get stored on heap if Object contains another object in it.
Static methods (in fact all methods) as well as static variables are stored in heap.
Please correct me if my understanding is wrong. Thanks.
There are some optimizations in the JVM that may even use the Stack for Objects, this reduces the garbage collection effort.
Classes are stored on a special part of the heap, but that depends on the JVM you use. (Permgen f.e. in Hotspot <= 24).
In general you should not have to think about where the data is stored, but more about the semantics like visibility and how long something lives. Your explanation in the questions looks good so far.
"Method Variables – object(User Defined) – are stored on heap but ..."
Wrong.
First, method variables are called local variables.
Let's consider
public static void main(String[] args) {
List<Integer> model = new ArrayList<Integer>();
Variable model is placed in the stack frame, not on heap. The referenced object generated with new ArrayList<Integer>() is placed in the heap but it is not a local variable.
The 3 things:
variable model
generated object
reference to that object, stored in a variable
are quite different, do not mess them up.
Object are stored in the Heap.
The object reference stored in the stack.
Static variable stored in the method area.
Example
abc obj=new abc();
abc object save in the heap and the object reference is stored in the stack.
static int i=10;
i variable stored in the method area.
I understand that variables of a method are stored in stack and class variables are stored in heap. Then where does the classes and objects we create get stored in Java?
Runtime data area in JVM can be divided as below,
Method Area : Storage area for compiled class files. (One per JVM instance)
Heap : Storage area for Objects. (One per JVM instance)
Java stack: Storage area for local variables, results of intermediate operations. (One per thread)
PC Register : Stores the address of the next instruction to be executed if the next instruction is native method then the value in pc register will be undefined. (One per thread)
Native method stacks : Helps in executing native methods (methods written in languages other than Java). (One per thread)
Following are points you need to consider about memory allocation in Java.
Note:
Object and Object references are different things.
There is new keyword in Java used very often to create a new object. But what new does is allocate memory for the object of class you are making and returns a reference. That means, whenever you create an object as static or local, it gets stored in heap.
All the class variable primitive or object references (which is just a pointer to location where object is stored i.e. heap) are also stored in heap.
Classes loaded by ClassLoader and static variables and static object references are stored in a special location in heap which permanent generation.
Local primitive variables, local object references and method parameters are stored in stack.
Local Functions (methods) are stored in stack but static functions (methods) goes in permanent storage.
All the information related to a class like name of the class, object arrays associated with the class, internal objects used by JVM (like Java/Lang/Object) and optimization information goes into the Permanent Generation area.
To understand stack, heap, data you should read about Processes and Process Control Block in Operating Systems.
All objects in Java are stored on the heap. The "variables" that hold references to them can be on the stack or they can be contained in other objects (then they are not really variables, but fields), which puts them on the heap also.
The Class objects that define Classes are also heap objects. They contain the bytecode that makes up the class (loaded from the class files), and metadata calculated from that.
The Stack section of memory contains methods, local variables and reference variables.
The Heap section contains Objects (may also contain reference variables).
after short google, I found a link to describe it, yes a youtube video link. ^_^
http://www.youtube.com/watch?v=VQ4eZw6eVtQ
The concept is quite simple :
Instance variables (primitive, Wrapper classes, references, objects (non-static)) - Heap
Local Variables , references - stack
Other data objects like : Class metadata, JVM code, static variables, static object references, static functions etc which earlier used to be in Permgen Space (till Java 7) are now being moved to Metaspace in JAVA 8.
PS : Metaspace is part of native memory, so no need to worry about OOM:Pergem Exeption now.
For more details : https://siddharthnawani.blogspot.com/
Local variables(method variables) + methods live on the stack. While Objects and their instance variable live on the heap.
Now, Reference variable can be local variable(if created inside method) or instance variable(if created inside class, but outside method). So reference variable can be anywhere, either stack or heap.
According to JVM Specification,
The classes and it's own constant pool, i.e static variables are stored in Method Area.
Here class means nothing but bunch of fields, methods and constants, these methods are in the form of instructions are stored in Method Area and can be identified by an address.
Objects are nothing but a filled class template that will be created in Heap Area, but the object reference is created in Stack.
public class Sample{
int field;
static int constant;
public void test(){
int localVariable=10;
Sample samp=new Sample();
}
}
In the example,
sample.class will go to Method Area, that means 'field', 'constant' and method 'test' are allocated in Method Area.
When the execution is started,
The object created by new Sample() will go to Heap but 'samp' is just a object reference which goes to stack and holds the address of object which is present in the Heap
For more information please check this link,
JVM Specification
In Java, a variable can either hold an object reference (s in String s="OOO" holds the reference to the object "OOO") or a primitive value (i in int i=10 holds 10). These variables can either be on the heap or the stack, depending on whether they are local or not and which flavor of the JVM you are using.
In the Java Virtual Machine 8 specification document (https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html), the memory organization pertaining to this is as follows.
Every Java thread has its own JVM stack.
It holds local variables and partial results, and plays a part in
method invocation and return.
There may be object references as well in the stack. The
specification does not differentiate between a primitive variable
and a reference variable as long as it is local. This stack is used using
units of data called frames. However,
Because the Java Virtual Machine stack is never manipulated directly
except to push and pop frames, frames may be heap allocated.
Therefore, it is upto the implementation of the JVM specification (like OpenJDK or Oracle), where the frames are located.
Every JVM instance has a heap. The heap is
... the run-time data area from which memory for all class instances and
arrays is allocated.
The actual memory holding the objects' data resides on the heap. The
heap is shared among all the JVM's threads. This also includes object
references which are part of objects ie instance variables.
For example, take the following classes.
class Moo{
private String string= "hello";
}
class Spoo{
private Moo instanceReferenceVariable = new Moo();
public void poo(){
int localPrimitiveVariable=12;
Set<String> localReferenceVariable = new HashSet<String>();
}
}
Here the object being referred to by the variable instanceReferenceVariable
would be on the heap, and hence all the instance variables of this object, like
string, will also be on the heap. Variables localPrimitiveVariable and
localReferenceVariable will be on the stack.
Method Area: The method area is a restricted part of the heap which
... stores per-class structures such as the run-time constant pool,
field and method data, and the code for methods and constructors,
including the special methods used in class and instance
initialization and interface initialization.
Run-time constant pool: This is a part of the method area.
Hope this was able to clarify things.
I am thinking about memory allocation in Java i.e in which
memory location methods, fields and objects are stored.
Suppose I have 2 classes
import java.util.*;
class ABC
{
int field;
List<Integer>l;
}
class XYZ
{
int x,y,z;
static int p;
void fun(ABC a){
a.field = 10;
a.l = new ArrayList<Integer>(10);
a.l.add(10);
}
}
public class Simulator{
public static void main(String[] arg){
XYZ tmp_1 = new XYZ();
ABC tmp_2 = new ABC();
tmp_1.fun(tmp_2);
System.out.println(tmp_2.l);
}
}
Now where will the memory be allocated for each of the data members,functions and objects be allocated ?
My thoughts are objects, data-members will be stored in Heap but I am not sure about functions and their data members ?
Yes, all objects are allocated on the heap. I.e.: everything created with new will be placed on the heap. All fields of such objects are thus also on the heap.
I suppose you are referring to local variables and parameters in functions. These are placed on the stack (for each call of the function). Note, however, that when function variables/parameters are of reference types then the actual object they point to is on the heap but the variable/parameter itself will be on the stack (similar to a pointer in C/C++). On the other hand, function variables/parameters of primitive types (like int, double, etc.) will be entirely on the stack. A slightly related but relevant to the topic is the concept of boxing.
Functions themselves are static code and are stored in a special part of the memory where all executable code resides. Note that all instances of a class share the same functions (i.e. "new functions" are not created with newly created objects, even if these functions are instance functions). Thus, when you call an instance function on an object, a special this reference is passed to that function (it's an implicit argument to the function). This is how the function knows on which objects it should act.
Here's a breakdown of how the different things that you refer or allude to are stored:
Local variables and method / constructor parameters can contain either primitive values or references to objects or arrays. (They cannot contain the objects or arrays themselves.) Locals and parameters are stored in activation frames (to use the JLS terminology), and these frames are stored on a thread's stack. Thread stacks are non-heap memory in typical JVMs.
Objects and arrays are represented in heap memory.
Instance fields (containing primitive or reference values) are stored in objects, and hence in the heap.
Array elements (either primitive or reference values) and the length of an array are stored in the array and hence in the heap.
Static fields are stored in special frames called static frames. These frames are stored in the heap.
The code of Java methods (in byte-code and native code form) is typically represented by code blocks that are stored in the heap.
Note that the above is based on what happens in a typical JVM. In fact, the Java Language Specification does not mandate that things are stored in a stack or a heap. The terms stack memory and heap memory hardly appear in the JLS at all, and it is conceivable that other memory organization schemes could be used.
Also, "the heap" is an over-simplification, because a HotSpot JVM / GC typically divides the heap into areas with different characteristics. For instance the "permgen" area of the heap (where static frames and code blocks are allocated) is only garbage collected rarely.
To complement previous answer:
The functions are stored in special area, but a reference to them is stored in the object (for non static functions).
Reference to static functions is stored in another area (you can think they are stored just next to static fields) (static memory area).
All objects are stored in heap (Object Pool), but the place of reference to them vary, local variables are in the stack, non static fields are stored in the object itself, so they are stored in the heap too.
Static references are placed in another special part of the memory, (although if they are references to Objects, they point to heap).