In Java we have written a code:
A a1;
a1 = new A();
How many bytes of memory is reserved when compiler compiles the code:
A a1;
References have a typical size of 4 bytes on 32-bit platforms and on 64-bits platforms with heap boundary less than 32Gb (-Xmx32G), and 8 bytes for this boundary above 32Gb. This means that a 64-bit JVM usually requires 30-50% more heap space.
A reference consumes the native word size of the platform it is running on. That is, 32-bit: 32 bits. 64-bit: 64 bits.
Stack Memory It stores the variables, references to objects, and partial results.
How much memory is allocated for an object? The overhead is 8 bytes on 32-bit, 12 bytes on 64-bit; and then rounded up to a multiple of 4 bytes (32-bit) or 8 bytes (64-bit).
That's not specified by the Java standard and thus you should not worry about it.
Technically, references are usually as big as the machine's word size, i.e. 32 bit on a 32 bit machine and 64 bit on a 64 bit machine, though some 64 bit JVMs use special magic to allow 32 bit references.
One pointer's worth of memory is used on the stack. That should be 32 bits (4 bytes) unless your machine's in 64-bits mode.
edit:
I see that some people are confused and think that the A object itself is allocated on the stack. That is not the case in Java: all objects are allocated on the heap (modulo JIT optimizations of course). The line A a1;
simply allocates pointer a1, initially set to NULL. The pointer itself is in the stack, though of course what it points to will be on the heap. The later call to new A()
will allocate an A object on the heap, and the size of that allocation does depend on what's in A.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With