'Memory usage of a char array with null values in Java

I'm attempting to calculate the memory usage of a trie search tree implementation in java. Each node contains a char array of size 52, with many of the indices being null values. I'm aware of the memory consumption of an array as well as each char in the array, but I'm unsure of the memory consumption of the null values. As far as I understand, JVM reserves space for the char and the reference to it, even while being null. Is this correctly understood? How many bytes would a null value in the array then take up, the same as if a char was available on that index?

Turning the array into an arrayList is not possible, and I don't seek advice on optimizing the memory usage, only advice on calculating the memory usage of said null values.

I'll happily answer any and all questions if needed!



Solution 1:[1]

The size of a char is always 16 bits, see https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Character.html#SIZE. The length of array times the element size plus the (Java Virtual Machine implementation dependent) size of the array's object header equals the amount of used memory.

As @Mark Rotteveel stated null is not a valid char.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Franck