Do Java primitives go on the Stack or the Heap? - java

I just know that the non-primitives (the objects) go on the heap, and methods go on the stack, but what about the primitive variables?
--update
Based on the answers, I could say the heap can have a new stack and heap for a given object? Given that the object will have primitive and reference variables..?

Primitives defined locally would be on the stack. However if a primitive were defined as part of an instance of an object, that primitive would be on the heap.
public class Test {
private static class HeapClass {
public int y; // When an instance of HeapClass is allocated, this will be on the heap.
}
public static void main(String[] args) {
int x=1; // This is on the stack.
}
}
With regards to the update:
Objects do not have their own stack. In my example, int y would actually be part of each instance of HeapClass. Whenever an instance of HeapClass is allocated (e.g. new Test.HeapClass()), all member variables of HeapClass are added to the heap. Thus, since instances of HeapClass are being allocated on the heap, int y would be on the heap as part of an instance of HeapClass.
However, all primitive variables declared in the body of any method would be on the stack.
As you can see in the above example, int x is on the stack because it is declared in a method body--not as a member of a class.

All local variables (including method arguments) go on the stack; objects and all their fields are stored in the heap. Variables are always primitives or references to objects.
Java implementations may actually store objects on the heap in such a way that it still complies with the specification. Similarly local variables may be stored in registers or become indistinct through optimisation.

primitives can be found in both places.
class Foo
{
public int x;
public static void Main()
{
int y = 3; // y is on the stack
Foo f = new Foo(); // f.x is probably on the heap
}
}
except you shouldn't really care unless you're building a JVM. A really clever optimizer might decide that since the Foo that f points to never escapes Main, and is never passed to another function that it is safe to allocate it on the stack.
With regards to the update:
The stack and the heap aren't distinguished by what is stored in them, but rather the operations provided for them. The stack allows you to allocate a piece of memory in a LIFO fashion, you can't deallocate a piece until all the pieces younger than it have also been deallocated. This conveniently aligns with how a call stack is used. You can put anything on the stack as long as it is ok for that thing to go away when your function returns. This is an optimization, as it is very quick to allocate and deallocate from a stack since it only supports being used in this manner. One could store all the local variables for a function on the heap in an implementation if one wanted to. The heap is more flexible, and consequently more expensive to use. It would not be accurate to say that an object has a stack and a heap, as I said, what distinguishes the stack from the heap is not what is in it, but the available operations.

Primitive values are allocated on the stack unless they are fields of an object, in which case they go on the heap. The stack is used for evaluation and execution, so no it doesn't make sense to say that objects with primitive fields have a stack—it is still considered to be part of the heap. Even Stack objects are allocated on the heap.

Related

How Java and C manage memory of local variable?

I'm considering about how Java and C manage variable in a scope.
In java, every iterator, I create a new object and then print it. The result say that each iterator I have a new Object.
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
while (true) {
Ideone object = new Ideone();
System.out.println(object);
}
}
}
And variable of scope in C. I do the same as I do in Java. Every iterator I create a variable and print its address. But the result make me confusing because it's returning the same address, because I think every iterator it create a new variable at a random address
#include <stdio.h>
int main() {
while (1) {
int variable;
printf("%p\n", &variable);
}
}
Can anyone tell me what's under the hood of Java and C ?? And why C do not create a random address for it's variable ?
EDIT 1:
I have another question about dynamic memory management in C like this:
#include <stdio.h>
int main() {
while (1) {
int *variable = malloc(sizeof(int));
printf("%p\n", variable);
}
}
In this case, they print different address after each iterator. And each address is more then the previous the constant size.
But if free the memory like this, now it print the same address
#include <stdio.h>
int main() {
while (1) {
int *variable = malloc(sizeof(int));
printf("%p\n", variable);
realloc(variable, 0);
}
}
Is C memory management do not generate random address for new variable ?
In Java, the new Ideone() objects lifetime is not bound to a scope, you could return it from a function.
In your C code, int variable; creates an object that is automatically destroyed when you reach the end of the scope it was defined in.
Many implementations of C use a stack to allocate such objects. A stack will always give you the same address when used this way.
This comparision is a bit like apple vs. oranges. Comparing Java's new to C's malloc would show a similar behavior.
You're comparing apples to kumquats here - you're printing out the value of object (which is the address of something explicitly created on the heap each time through the loop) vs. the address of variable (which is an auto object that's typically allocated from the runtime stack).
variable has auto storage duration, meaning that storage for it is only guaranteed to be allocated over the lifetime of its enclosing scope (i.e., the body of the loop). However, as a matter of practice, most C compilers will allocate space for all auto variables in a function at function entry, even if the scope of those variables is limited to a smaller block within the function. IOW, the space for variable is allocated once, so its address doesn't change from iteration to iteration. And, given how most C implementations manage auto objects, it would be allocated from the same address anyway if it were allocated and deallocated with each loop iteration.
A more direct comparison would be looking at the address of the object variable itself, not its value, but I'm not sure how you would obtain that information (been a long time since I've done any Java).
In your Java code, you explicitly create a new object with every run in the loop. Thus, it is very likely that the different objects yield different memory addresses.
In you C-code, in contrast, you do not "create" anything, because variables are actually not "created". They are concepts of the programming language, and the compiler may decide when, where, and how often it reserves memory for the variable to hold a value. In practice, local variables are placed on the stack once at the beginning of a function or a loop, so it seems as if it were "created" only once, but this is actually something you cannot rely on.
Note, however, that the situation becomes a different one if you allocate "objects" in C as well. This would be rather comparable then to what Java does (in Java, all class-based types are handled through a pointer, but this isn't exposed to the user):
#include <stdio.h>
int main() {
while (1) {
int *variable = malloc(sizeof(int));
printf("%p\n", variable);
}
}
Besides memory leaks and running out of memory, this will print different memory addresses with each iteration.
Java use virtuel machine JVM. The garbage collection delete the variables when it's not needed any more.
In C the variables are stored in the stack or heap which you need you use malloc to allocate memory and free to deallocate.
Your output shows the address of variable in hexadecimal where in memory it's located and it's compilers decision in which memory address it should be stored.
local variables are put on the stack since in your code you did not used malloc to allocate memory on the heapit will give you the same address because stack is Last-in-first-out and your loop PUSH and POP in the same address, but if you close your terminal and run it again it will give you different address.
Close terminal and reopen run again it gives different address.

What happens when JVM executes new key word to create an object?

I know JVM uses stack and heap for allocation of memory for object reference, object value and memory for methods. But I am confused about the terminologies: METHOD AREA, HEAP and JAVA STACK and I have few question's.
When we say "ClassName obj = new ClassName()", new creates an object on the HEAP(the instance variables and static variables too) and what is returned to the reference(obj)? Some people use to say it is CLASS TYPE, does it mean the hash code?
When new creates the object on the heap, at the same time: i)the methods,corresponding to that object ii)local variables and iii)the reference to that object are stored as part of STACK( is it JAVA STACK?). If so, then what does METHOD AREA do? Or am I wrong?
What is the amount of memory allocated for that object?
i. for object reference
ii. for object values(it depends on the local variables)
iii. will there be a memory allocated to point the object's methods?( because the non-static members are not shared among the objects and a separate copy is maintained for each objects including the methods).
By the way, where does static methods are stored?
When we say "ClassName obj = new ClassName()", new creates an object
on the HEAP(the instance variables and static variables too) and what
is returned to the reference(obj)? Some people use to say it is CLASS
TYPE, does it mean the hash code?
Yes new creates Object on the HEAP. Heap is a memory place where the objects and its instance variable are stored. Not static variables since static variables doesn't belong to Object it belongs to class so are stored on PermGem Sections (class related data, not instance related).
What is Returned : the reference(pointer/memory address) i.e hashcode
When new creates the object on the heap, at the same time: i)the
methods,corresponding to that object ii)local variables and iii)the
reference to that object are stored as part of STACK( is it JAVA
STACK?). If so, then what does METHOD AREA do? Or am I wrong?
since All threads share the same method area methods don't corresponds to Objects it belongs to class
what does METHOD AREA do :The method area stores per-class information, like Run Time Constant Pool, Method code, The method's return type (or void) etc
What is the amount of memory allocated for that object? i. for object
reference ii. for object values(it depends on the local variables)
iii. will there be a memory allocated to point the object's methods?(
because the non-static members are not shared among the objects and a
separate copy is maintained for each objects including the methods).
Amount of Memory for Object Reference: it depends as on many VMs the size of a reference is the native pointer size and for (iii) above point already cleared that
I know JVM uses stack and heap for allocation of memory for object reference
correct.
object value
I assume you means the object's header and fields.
and memory for methods.
Methods are not stored in the heap, or stack. When you profiler the heap usage or set the maximum heap size, the use of methods makes no difference as they are not on the heap in the Oracle or OpenJDK JVM.
They are stored in the PermGen or MetaSpace or some other space depending on which JVM you are using.
But I am confused about the terminologies: METHOD AREA,
From Method Area in Java
The Java Virtual Machine has a method area that is shared among all Java Virtual Machine threads. The method area is analogous to the storage area for compiled code of a conventional language or analogous to the "text" segment in an operating system process. It 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 (§2.9) used in class and instance initialization and interface initialization.
HEAP
Shared space for storing objects. This is usually one continuous region of native memory managed by the JVM.
and JAVA STACK
The thread's stack which is actually a native thread stack on most JVM.
When we say "ClassName obj = new ClassName()", new creates an object on the HEAP(the instance variables and static variables too)
It might, but it can also eliminate the object with escape analysis, placing the fields on the stack, and possibly eliminating those.
and what is returned to the reference(obj)?
Correct, Java only has references and primitives (if you ignore the void type which is neither)
Some people use to say it is CLASS TYPE,
The reference is defined by giving the type of the reference which is a class or interface.
does it mean the hash code?
A hash code is a hash value for the object. It is not releated to anything else you have mentioned.
When new creates the object on the heap,
When you create a new object on the heap, you just create space for the header of the object (which points to the class and it's methods) and space for it's fields. (Those the JVM doesn't optimise away)
at the same time: i)the methods
The methods are loaded/compiled in various stages. The methods are loaded as they are needed for the first time and later if they are compiled.
corresponding to that object ii)local variables
Local variables are on the stack, not on the heap, not in the object.
iii)the reference to that object are stored as part of STACK( is it JAVA STACK?).
The Java Stack, is the Stack, is the native stack.
If so, then what does METHOD AREA do?
Store the code for the methods.
What is the amount of memory allocated for that object?
About 8-12 bytes per header, space for each primitive field and reference and alignment padding of 8 or 16 bytes (32 GB - 64 GB heaps).
i. for object reference
Typically this is 32-bit on 64-bit JVMs (With compressed oops). If you have more than 64 GB heap it will be 64 -bit.
ii. for object values(it depends on the local variables)
Local variables are on the heap not the object.
iii. will there be a memory allocated to point the object's methods?
Method memory usage is not visible to you. It is not on the heap, nor something you can measure on a per method basis. I don't know of a profiler which will even show you this.
( because the non-static members are not shared among the objects and a separate copy is maintained for each objects including the methods).
That sounds like an insane waste of space, and it is, which is why the JVM does do that. There is only one copy for a method, regardless of the number of instances.
By the way, where does static methods are stored?
With all the other methods. There is no difference between a static method and a non-static method except a non-static method must take an instance as it's first argument at the JVM level. (And there is a bit in the modifiers to say whether it is static or not)

If the object name is a reference, where the object stored? [duplicate]

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.

When is memory space allocated to a variable?

Does the compiler allocate 4 bytes of memory when the variable is declared:
int a;
Or does it allocate memory when a value is assigned to it:
a = 5;
When is memory allocated? During variable declaration or initialization?
The variable is allocated when the structure containing it is allocated.
For a local variable in a method this is (with some caveats) when the method is invoked.
For a static variable this is when the class is "initialized" (which happens some time after it's loaded and before it's first used).
For an instance variable this is when the instance is created.
In most programming languages the compiler is allowed to choose when to allocate space for variables. The only thing you are guaranteed, is that the storage will be available if and when you need it.
A short anecdote...
The C programming language used to require that all variables used in a method be declared at the top of the method. This was because compilers used to reserve storage for all stack (local) variables in a method as soon as you entered the method. Today that requirement doesn't exist in part because compilers are a lot smarter.
Most compilers of C-like languages will defer allocation of instances until first use for optimized code. The REALLY tricky thing here is that the first use may not be where you think it is, and it may not occur at all. For example, if you have the following code:
int foo(int x) {
int y = 5;
if (x > 5)
y += x;
return y;
}
You might think the first use is when you assign 5 to y, but the compiler could optimize that code to something more like:
int foo(int x) {
if (x > 5)
return 5 + x;
return 5;
}
In this code y never really exists at all.
TL;DR - The compiler actually isn't guaranteed to allocate memory on declaration or use. Trust the compiler, it is (usually) smarter than us all.
When we have “declared'' a variable, we have meant that we have told the compiler about the variable; i.e. its type and its name, as well as allocated a memory cell for the variable (either locally or globally). This latter action of the compiler, allocation of storage, is more properly called the definition of the variable.
Simply Definition = Variable Declaration + Variable initialization
JVM divides memory into stack and heap memory. Whenever we declare new variables and objects, call new method, declare a String or perform similar operations, JVM designates memory to these operations from either Stack Memory or Heap Space.
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.

what actually compiler does when we declare variable?

let have an example.
public class test {
public static void main(String args[]) {
int a=5,b=4;
int c=a+b;
int d=9;
System.out.println("ANSWER PLEASE..");
}
}
Now when we execute this code what os does?
It first create a variable named a and alocates a memory address similar things for b and c.
now what happen to d. os creates a new memory address or it just reffer to the address of c as the value is same.
First of all, the compiler doesn't do much. It basically translates it into class-files / bytecode. In the bytecode there is a number called "max locals" which tells how many local variables are required to run the method.
The JVM on the other hand, which reads this information and runs the code makes sure memory is allocated on the stack frame to fit the required variables. How much it asks for is highly implementation dependent, and it may very well optimize the whole thing, and allocate fewer bytes than what's indicated by the code.
what happen to d. os creates a new memory address or it just reffer to the address of c as the value is same.
This is tagged Java. So let's keep the OS out of it. Everything happens in memory managed by the JVM, which is allocated in big chunks in advance.
You are talking about primitive data types. Those are easy, as they are stored by value, not as references to objects living elsewhere.
You are talking about local variables. Those are allocated on the running thread's call stack (not in heap memory). Since they are primitive here, too, this does not involve the heap at all.
In your case, there is memory allocated (on the stack), for the four integers. Each of them contains the value assigned to it, not a reference. Even if the same value is assigned to all of them, they exist separately. The memory is "freed" (not really freed, but no longer used by the thread) when the method returns.
If those were not integers, but Objects, you could "share pointers" (to objects on the heap), but integers are stored by value (four bytes each).

Categories