Suppose a class contains a final
variable. Why is new space allocated for final variable every time an object of the class is created even though its value can't be changed? Why its memory allocation is not like a static
variable?
Consider this example:
public class Example {
public final int someNum;
// constructor
public Example(int n) {
someNum = n;
}
}
Here in this example, every object of this class might have a different value for someNum
, even though it is a final
variable. Therefore new space must be allotted for every instance of the class.
While you can't assign a new value to a final
variable, each instance of the class can have a different value, so each instance needs to allocate its own memory for its own member.
For final variables in Java, it is not necessary to assign a value when declared. A final variable can be assigned value later, but only once. As a different value can be assigned it needs different memory allocation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With