java memory optimization for final variables : Assume that I have class circle, and I have created 100 objects for that class. then which one of the below code takes lesser memory for all objects?
Final double pi = 3.14;
static final double pi=3.14;
double pi = 3.14;
we can't simply guess it, it depends on size of double.
Using static final double pi=3.14 will have good impact on memory. since this is a static variable, for which memory will be allocated only once, no matter how many objects you have created for circle class.
If you don't use static, then pi will become instance variable and it will be copied into all circle objects. Which will waste your memory unnecessarily.
We know that pi is a constant, so no point in creating same pi value so many times. Just make it static to create pi value only once.
Back To Top