I recently came across a class in which the following field was declared:
private final int period = 1000;
In this particular case, the author assumed that it is also static, and since the value cannot be changed at any point, there was no real functional reason not to declare it static, but I wondered how Java handles final and final static primitives.
In particular:
1) How are final static primitives stored? Are they simply compiled directly into the expressions in which they are used?
2) If they are actually reserved for storage, should each instance of the containing class maintain a reference to this location? (in this case, for primitives less than 4 bytes, each instance of the class will actually be larger than if it simply included the primitive directly, as it would in a non-static case)
3) Are the compilers smart enough to determine that in cases like the above, the variable is “effectively static” because it would be impossible to have different instances containing different values, and therefore optimize it like a finite static
java private static final
Dusty
source share