Memory Usage in Java
Remi Forax
forax at univ-mlv.fr
Fri Aug 8 16:47:00 UTC 2025
C (and Java) tricks you to think that a "short" has a single representation but this is not true,
it has two representations, one on stack (local variables) and one on heap (fields and array elements).
On stack (or on registers because you do not control exactly where a local variable is stored), values are either 32 or 64 bits
This is dues to the fact that 64 bits CPUs only have 32bits / 64 bits registers.
On heap, everything is a multiple of 8 bits
(Different CPUs may have different alignment constraints depending how you access the memory (plain, volatile, etc) but that's another story).
So on stack a char is 32 bits and on heap, a char is 16 bits.
Because of that, when you want to compute something using a char, the compiler will have to convert it from char to a 32 bits integer
(the conversion has to propagate the sign bit so the 32 bits value is the same as the 16 bits value).
That's why in Java, the result of the addition of two shorts is an int,
short s = ...
short s2 = ...
s + s2. // this is an int
I hope it helps.
regards,
Rémi
> From: "Kenneth Fogel" <kfogel at dawsoncollege.qc.ca>
> To: "discuss" <discuss at openjdk.org>
> Sent: Friday, August 8, 2025 6:10:32 PM
> Subject: Memory Usage in Java
> Please let me know where I might ask this question or find the answer if this is
> not the right place.
> In a book I am working on I am writing about how Java deals with memory
> allocation for the primitive types on a 64 bit CPU. I know the size of
> primitive variable types such as byte is 1, int is 4, etc. and that the size is
> related to the range of allowable values. From my C/C++ days I learned that the
> actual amount of RAM used was related to the word size of a CPU so that when a
> byte is read you are really reading a word. This meant to me that if I had 10
> variables of type byte, not in an array, it would consume 80 bytes of RAM. From
> my reading it appears to be the same in Java except for arrays. Is this
> accurate? For example, an int is 4 bytes but when Java runs on a 64 bit CPU is
> it really reading and writing 8 bytes? If it is, can we say that the 4 bytes of
> padding is RAM dead space that cannot be used for anything else?
> Thank you for your time,
> Ken Fogel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/discuss/attachments/20250808/85af439f/attachment-0001.htm>
More information about the discuss
mailing list