Java – how byte data types are used to hold memory in large arrays
I see this in the Java documentation My question is how do byte data types store memory in large arrays I'm confused about it
Thank you in advance
Solution
Its meaning is very simple
Suppose I have 40 "numbers" to store If I store them in:
byte[] numbers = new byte[40];
If I store them below, it will take up less space:
int[] numbers = new int[40];
Why? Because in an array, 40 byte instances occupy 40 bytes of memory, but 40 int instances occupy 40 x 4 = 160 bytes of memory
matters needing attention:
>Obviously, this only works if the number is small enough to be expressed as bytes... There is no overflow; That is, they must be in the range of - 128 to 127 > this does not apply to simple variables In Java, byte variables and int variables usually occupy 4 bytes each (this is a low-level JVM and needs a lot of explanation...) > I'm masking the fact that heap memory may be allocated at a coarser granularity than 4 bytes The allocation granularity is usually 8 bytes However, for large arrays, the contribution of allocation granularity is negligible