How much memory will JVM Allocate to 1) Static String 2) Static Integer
(To simplify things, I'll assume we are talking about a 32bit JVM. Also note that these numbers are approximate, and JVM specific.)
The easy one first - each static Integer
variable occupies 4 bytes of memory for the reference plus 4 bytes + 1 object header (typically 8 bytes IIRC). Grand total - 16 bytes.
(And if you are talking about static int
variables, it is 4 bytes total per int
.)
A static String
variable is a bit more complicated ... and more expensive:
- The static reference variable is 4 bytes.
- The
String
object has 4 x 4byte fields + 1 x 2 word object header: that's 24 bytes.
- One of those fields refers to a char array which has a 3 word header and requires
(string.length() + 3) / 4
bytes for the content - that's 12 + some multiple of 4 bytes.
- If the String value is a compile time constant then the String will be interned, and that will add a few extra bytes overhead for the string pool hash table entry. (32 bytes
would be a reasonable guess.)
Add that all up and you get (say) 80+ bytes per string, depending on string length. But nearly all of those bytes are the representation of the (interned) String itself. Only 4 bytes are due to the use of a static
.
I am exploring this issue as I am getting Heap Memory Out of Memory Exception, I have in my application 8 constants file and each file has almost near to 300 Static Constants.
That's insignificant. The OOME is almost certainly due to something else.
Is that a good practice to declare all the constants as a Static or any other practice can I Follow?
It is good practice to declare real constants as statics, up to a point.
However, large numbers of constants in the source code gets unwieldy, and you eventually run into compilation errors due to limits in the format of a bytecode file. At that point (and probably well before then) you should move the constants out of your source code and into a database or configuration file.
You are likely to run into the bytecode-format-imposed limit well before memory usage becomes a significant issue.