Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Memory Usage upon variable declaration?

With regards to memory efficiency I have the following question:

It is imperative that correct Data types are used for the corresponding variables. Representing a numeric value of 1 as a byte requires an eighth of the memory a long(but please correct me if I am wrong). My question though is if memory allocation/deduction takes place upon defining your variable type or initialization? It may seem odd, but I ask in relation to global variables that do not need to be initialized as they have defaults as apposed to local variables. I would also like to know if there is a default size for Object data types? I presume this is based on the JVM (32bit vs 64 bit)?

like image 394
thejartender Avatar asked Nov 03 '22 00:11

thejartender


1 Answers

It is imperative that correct Data types are used for the corresponding variables.

Of course. Java is a strongly typed language. Your point?

Representing a numeric value of 1 as a byte requires an eighth of the memory a long(but please correct me if I am wrong).

You're wrong. Depending on what other variables and types are declared adjacently, it may take 4 or even 8 bytes, depending on the padding used by the JVM.

My question though is if memory allocation/deduction takes place upon defining your variable type or initialization?

Neither. It happens at allocation time, i.e. at new time, rather than during the constructor for example.

It may seem odd, but I ask in relation to global variables that do not need to be initialized as they have defaults

All variables need to be initialized. You just don't have to write initializer code in the case of static or instance variables. The word 'global' in reference to Java has no meaning.

as opposed to local variables.

It doesn't make any difference what it is. The variable still has to have space allocated to it and a value stored in it, whether static, instance, or method-local.

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

The question is meaningless. Instances of the class Object are always of the same size, which carefully isn't documented or specified anywhere, and is therefore free to vary with the JVM. Instances of other classes ditto. There is no 'default' anywhere in any useful sense that I can see.

like image 65
user207421 Avatar answered Nov 10 '22 03:11

user207421