Java memory usage when declaring a variable?

As for memory efficiency, I have the following question:

It is imperative that the correct data types are used for the relevant variables. Representing the numeric value of 1 as byte , it takes an eighth of the memory for a long time (but please correct me if I am wrong). My question is, does memory allocation / subtraction occur when determining the type of variable or initialization? This may seem strange, but I ask for global variables that do not need to be initialized, since they have default values ​​associated with local variables. I would also like to know if there is a default size for Object data types? I believe this is based on the JVM (32 bit vs 64 bit)?

+4
source share
1 answer

It is imperative that the correct data types are used for the relevant variables.

Sure. Java is a strongly typed language. Your point

Presenting the numeric value of 1 as a byte, an eighth of the memory is required (but please correct me if I am wrong).

You're wrong. Depending on which other variables and types are declared contiguously, 4 or even 8 bytes may be required depending on the pad used by the JVM.

Perhaps my question is, does memory allocation / subtraction occur when determining the type of variable or initialization?

None. This happens during distribution, i.e. in new time, and not during constructor, for example.

This may seem strange, but I ask for global variables that do not need to be initialized, since they have default values

All variables must be initialized. You just don't need to write initialization code in case of static or instance variables. The word "global" in relation to Java has no meaning.

unlike local variables.

It doesn't matter what it is. The variable should still have space allocated and the value stored in it, be it static, instance, or method-local.

I would also like to know if there is a default size for Object data types? I believe this is based on the JVM (32 bit vs 64 bit)?

The question is pointless. Instances of the Object class are always the same size, which is not carefully documented or specified anywhere, and therefore can vary freely depending on the JVM. Instances of other classes too. In any useful sense that I see, there is no "default".

+1
source

All Articles